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

编程入门 行业动态 更新时间:2024-10-27 22:27:50
本文介绍了所有tkinter函数在程序启动时运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个非常奇怪的问题,在使用tkinter之前我从未有过。无论我为按钮或菜单项等小部件设置命令,该命令都会在应用程序启动时运行。基本上,该命令不会等到单击该小部件才能运行。在我的代码中,我知道我没有打包按钮,这是为了显示小部件甚至不必被拖到屏幕上以发生此问题。有人知道可能是什么原因造成的吗?

I am having a very weird problem that I've never had before when using tkinter. Anywhere that I set a command for a widget such as a button or a menu item, the command runs when the application starts up. Basically the command doesn't wait until the widget is clicked to run. In my code, I know that I did not pack the button, this was to show that widget don't even have to be drawn onto the screen for this problem to occur. Does anybody know what could be causing it? Thanks!

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

推荐答案

删除命令定义中的()。现在,您正在调用函数并将返回值绑定到 command 参数,而您需要绑定函数本身,以便稍后调用函数。

Remove the ()s in your command definitions. Right now, you are calling the function and binding the return values to command parameter whereas you need to bind the functions itself so that later on they could be called.

所以这样一行:

So a line like this:

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

应该是这样的:

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

(你实际上在一个地方做了这个: filemenu.add_command(label =Exit,command = app.quit) )

(You actually do this in one place correctly: filemenu.add_command(label="Exit", command=app.quit))

更多推荐

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

本文发布于:2023-11-05 06:24:49,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:启动时   函数   程序   tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!