我有一個非常奇怪的問題,在使用tkinter之前我從未有過。無論我爲按鈕或菜單項等小部件設置命令,該命令都會在應用程序啓動時運行。基本上,該命令不會等到單擊該小部件才能運行。在我的代碼中,我知道我沒有打包按鈕,這是爲了顯示小部件甚至不必被拖到屏幕上以發生此問題。有人知道可能是什麼原因造成的嗎?謝謝!當程序啓動時運行所有的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()
感謝您的回答!這就是訣竅! – SilverSerpent 2012-01-31 03:34:20