python 以主程序运行_python – 程序启动时运行所有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()

最佳答案

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

这样的一行:

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值