首页 文章

按钮不工作的Tkinter命令[重复]

提问于
浏览
-2

这个问题在这里已有答案:

我正在尝试让我的程序根据下拉菜单中选择的变量更改文本,但是激活命令的按钮似乎不起作用 . 从我所看到的,一旦程序加载,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

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

  • 1

    您的主要问题是在设置 command=self.food() 时不需要括号:

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

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

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

    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()
    

相关问题