按钮的 Tkinter 命令不起作用 [英] Tkinter command for button not working

查看:43
本文介绍了按钮的 Tkinter 命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的程序根据下拉菜单中选择的变量更改文本,但激活命令的按钮似乎不起作用.从我所见,选择函数会在程序加载后运行,然后再也不会运行,无论我何时单击按钮.

I'm trying to make my program change the text based on a variable selected in the dropdown menu, but the button to activate the command doesn't seem to be working. From what I can see, the select function run's once the program is loaded and then never again, regardless of when I click the button.

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 的初学者,在开始制作完整的应用程序之前,我正在尝试弄清楚基础知识.提前致谢:)

I'm a beginner on Tkinter, and I'm trying to figure out the basics before I go into making my full app. Thanks in advance :)

推荐答案

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

Try changing button = Button(root, text = "Choose", command=self.select()) to button = Button(root, text = "Choose", command=self.select). Note the removed parentheses after self.select. This way, the method only gets referenced and not actually executed until you press the button.

这篇关于按钮的 Tkinter 命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆