2012-01-31 51 views
2

我有一個非常奇怪的問題,在使用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() 

回答

12

刪除您的命令定義中的()。現在,您正在調用函數並將返回值綁定到command參數,而您需要綁定函數本身,以便稍後調用它們。

所以這樣一行:

filemenu.add_command(label="New...", command=self.new()) 

實際上應該是這樣的:

filemenu.add_command(label="New...", command=self.new) 

(你真正做到這一點在同一個地方正確:filemenu.add_command(label="Exit", command=app.quit)

+0

感謝您的回答!這就是訣竅! – SilverSerpent 2012-01-31 03:34:20

7
filemenu.add_command(label="Open...", command=self.open()) 
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_command(label="Open...", command=self.open) 
filemenu.add_command(label="New...", command=self.new) 
filemenu.add_command(label="Open...", command=self.open) 
filemenu.add_command(label="Save", command=self.save) 
+0

感謝您的答覆!我沒有意識到,實際上稱爲功能。問題解決了! – SilverSerpent 2012-01-31 03:10:56

相關問題