我试图让我的程序根据下拉菜单中选择的变量更改文本,但激活命令的按钮似乎不起作用。从我所看到的,选择函数在程序加载后运行,然后再也不会运行,无论我何时单击按钮。
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()
Run Code Online (Sandbox Code Playgroud)
我是 Tkinter 的初学者,在开始制作完整的应用程序之前,我试图弄清楚基础知识。提前致谢 :)
尝试更改button = Button(root, text = "Choose", command=self.select())为button = Button(root, text = "Choose", command=self.select). 请注意 self.select 之后删除的括号。这样,该方法只会被引用而不会实际执行,直到您按下按钮。
| 归档时间: |
|
| 查看次数: |
12799 次 |
| 最近记录: |