按钮的 Tkinter 命令不起作用

编程入门 行业动态 更新时间:2024-10-28 20:27:38
本文介绍了按钮的 Tkinter 命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 07:15:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   不起作用   命令   Tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!