所有tkinter函数在程序启动时运行

5 投票
2 回答
5471 浏览
提问于 2025-04-17 12:00

我遇到了一个很奇怪的问题,这是我以前从来没有碰到过的,使用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()

2 个回答

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)
16

在你的命令定义中去掉()。现在你是在调用这个函数,并把返回的值绑定到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)

撰写回答