按钮的Tkinter命令不起作用

时间:2017-08-16 09:41:55

标签: python tkinter

我正在尝试让我的程序根据下拉菜单中选择的变量更改文本,但是激活命令的按钮似乎不起作用。从我所看到的,一旦程序加载,select函数就会运行,然后再也不会再次运行,无论我何时单击按钮。

from Tkinter import *

class App:

    def __init__(self, root):
        self.title = Label(root, text="Choose a food: ",
                           justify = LEFT, padx = 20).pack()
        self.label = Label(root, text = "Please select a food.")
        self.label.pack()

        self.var = StringVar()
        self.var.set("Apple")
        food = ["Apple", "Banana", "Pear"]
        option = apply(OptionMenu, (root, self.var) + tuple(food))
        option.pack()

        button = Button(root, text = "Choose", command=self.select())
        button.pack()

    def select(self):
        selection = "You selected the food: " + self.var.get()
        print(self.var.get()) #debug message
        self.label.config(text = selection)

if __name__ == '__main__':
    root = Tk()
    app = App(root)
    root.mainloop()

我是Tkinter的初学者,在我制作完整的应用程序之前,我正试图找出基础知识。在此先感谢:)

3 个答案:

答案 0 :(得分:2)

尝试将button = Button(root, text = "Choose", command=self.select())更改为button = Button(root, text = "Choose", command=self.select)。请注意self.select后删除的括号。这样,只有按下按钮才会引用该方法,而不会实际执行该方法。

答案 1 :(得分:1)

您的主要问题是在设置command=self.food()

时不需要括号
button = Button(root, text="Choose", command=self.select)

作为旁注,您生成OptionMenu的方式有点不寻常。您可以使用以下代码,这与代码的其余部分更加一致:

option = OptionMenu(root, self.var, *food)

答案 2 :(得分:0)

enter image description here命令参数文档,符合tkinterbook

(按下按钮时调用的函数或方法。回调可以是函数,绑定方法或任何其他可调用的Python对象。如果不使用此选项,则当用户按下按钮时不会发生任何操作。)

*****************************修改后的代码**************** ***************

from Tkinter import *

class App:

    def __init__(self, root):
        self.title = Label(root, text="Choose a food: ",
                           justify = LEFT, padx = 20).pack()
        self.label = Label(root, text = "Please select a food.")
        self.label.pack()

        self.var = StringVar()
        self.var.set("Apple")
        food = ["Apple", "Banana", "Pear"]
        option = apply(OptionMenu, (root, self.var) + tuple(food))
        option.pack()

        button = Button(root, text = "Choose", command=self.select)
        #use function name instead of aclling the function
        button.pack()

    def select(self):
        selection = "You selected the food: " + self.var.get()
        print(selection) #debug message
        self.label.config(text = selection)

if __name__ == '__main__':
    root = Tk()
    app = App(root)
    root.mainloop()