尝试使用tkinter编写Python工具,但是窗口出现了?

时间:2019-01-01 17:18:45

标签: python tkinter

我正在尝试构建一个简单的总和计算器,但是tkinter窗口显示为空而没有任何错误。我正在最新的MacOS-10.14和最新的Python-3.7上的PyCharm中运行它。

我真的无法弄清楚我想念的是什么。我敢肯定这很明显,但是我想,我只需要一双新鲜的眼睛即可。 任何帮助将不胜感激。

代码如下:

import tkinter as tk


class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)

        self.pack()


# create the application
app = Application()
app.master.title("Sumator")
app.master.minsize(width=1000, height=500)

# start the program
app.mainloop()


def __init__(self, master=None):
    super().__init__(master)

    self.pack()
    self.create_widgets()


def create_widgets(self):
    # create widgets
    self.firstNumberEntry = tk.Entry()
    self.plusSign = tk.Label(text="+")
    self.secondNumberEntry = tk.Entry()
    self.equalSign = tk.Label(text="=")
    self.resultLabel = tk.Label(text="Result...", bg="green", fg="white")
    self.calculateButton = tk.Button(text="Calculate", command=self.calculate)

    # place widgets
    self.firstNumberEntry.pack(side="left")
    self.plusSign.pack(side="left")
    self.secondNumberEntry.pack(side="left")
    self.equalSign.pack(side="left")
    self.resultLabel.pack(side="left")
    self.calculateButton.pack(side="left")


def calculate(self):
    first_value = float(self.firstNumberEntry.get())
    second_value = float(self.secondNumberEntry.get())
    result = first_value + second_value
    self.resultLabel.config(text=str(result), bg="green", fg="white")

1 个答案:

答案 0 :(得分:1)

您的类方法是在类外部定义的,并且您有两次def __init__(self, master=None)

import tkinter as tk


class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()


    def create_widgets(self):
        # create widgets
        self.firstNumberEntry = tk.Entry()
        self.plusSign = tk.Label(text="+")
        self.secondNumberEntry = tk.Entry()
        self.equalSign = tk.Label(text="=")
        self.resultLabel = tk.Label(text="Result...", bg="green", fg="white")
        self.calculateButton = tk.Button(text="Calculate", command=self.calculate)

        # place widgets
        self.firstNumberEntry.pack(side="left")
        self.plusSign.pack(side="left")
        self.secondNumberEntry.pack(side="left")
        self.equalSign.pack(side="left")
        self.resultLabel.pack(side="left")
        self.calculateButton.pack(side="left")


    def calculate(self):
        first_value = float(self.firstNumberEntry.get())
        second_value = float(self.secondNumberEntry.get())
        result = first_value + second_value
        self.resultLabel.config(text=str(result), bg="green", fg="white")

# create the application
app = Application()
app.master.title("Sumator")
app.master.minsize(width=1000, height=500)

# start the program
app.mainloop()