【发布时间】:2012-02-22 20:01:15
【问题描述】:
我在使用 tkinter 时遇到了一个以前从未遇到过的非常奇怪的问题。在我为小部件(例如按钮或菜单项)设置命令的任何地方,该命令都会在应用程序启动时运行。基本上,该命令不会等到单击小部件才运行。在我的代码中,我知道我没有打包按钮,这是为了表明甚至不必将小部件绘制到屏幕上即可发生此问题。有谁知道可能是什么原因造成的?谢谢!
from tkinter import *
class menuItems(object):
def __init__(self):
menubar = Menu(app)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New...", command=self.new())
filemenu.add_command(label="Open...", command=self.open())
filemenu.add_command(label="Save", command=self.save())
filemenu.add_separator()
filemenu.add_command(label="Exit", command=app.quit)
menubar.add_cascade(label="File", menu=filemenu)
app.config(menu=menubar)
def new(self):
pass
def open(self):
pass
def save(self):
print("You have saved the file")
def this_should_not_run():
print("Yay! I didn't run!")
def this_will_run_even_though_it_should_not():
print("You can't stop me!")
def init():
global app, menu
app = Tk()
app.title("Words with Python")
app.geometry("800x500+50+50")
menu = menuItems()
frame = Frame(app)
scrollbar = Scrollbar(frame, orient=VERTICAL)
textbox = Text(frame, yscrollcommand=scrollbar.set)
scrollbar.config(command=textbox.yview)
scrollbar.pack(side=RIGHT, fill=Y)
textbox.pack(side=LEFT, fill=BOTH, expand=1)
frame.pack(fill=BOTH, expand=1)
button = Button(app, text="Nothing", command=this_will_run_even_though_it_should_not())
return
init()
app.mainloop()
【问题讨论】: