TKINTER - 函数在放入类时行为不端

时间:2016-07-30 04:38:49

标签: python tkinter

在创建一个在tkinter中运行的对话框时遇到一些麻烦。我在独立脚本中运行的代码(剥离了所有细微差别)是:

from tkinter import *

def create_window():
    window = Toplevel(root)

root = Tk()
b = Button(root, text="Create new window", command=create_window, height=10, width=50)
b.pack()

root.mainloop()

这很有效。

然而,当我把它放到一个类(如下面)时,无论你是否按下按钮,对话框都会打开。

from tkinter import *

class MyApp:
    def __init__(self, root):
        self.root = root

    def layout(self):
        button = Button(self.root, text='click to create popup', \
                        height=5, width=50, command=self.create_popup())
        button.pack()

    def create_popup(self):
        window = Toplevel(root)
        window.title('this is the title')
        label1 = Label(window, text='this is label text')
        label1.pack()

    def run(self):
        self.layout()
        self.root.mainloop()

if __name__ == '__main__':
    root = Tk()
    app = MyApp(root)
    app.run()

我错过了一些东西,我完全不知道发生了什么。有什么我不会去的吗?

谢谢!

编辑:解决了,从self.create_popup()中移除了括号,然后就可以了。

0 个答案:

没有答案