2012-01-31 52 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

相关问题