到目前为止,我有一个非常简单的程序,只有几个带有事件的按钮。但是,当我运行程序时,一旦按钮启动,按钮事件就会触发。
我的代码中的麻烦部分如下所示:
def initUI(self):
self.parent.title("Windows")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
abtn = Button(self, text="Open", command=load_file(area))
abtn.grid(row=1, column=3)
cbtn = Button(self, text="Close", command=self.parent.destroy)
cbtn.grid(row=2, column=3, pady=4)
我一行一行地运行它,load_file(它是一个打开的文件对话框,区域是我之前初始化的 Canvas )事件甚至在下一个按钮初始化或窗口可见之前就打开了。 尽可能具体:我不希望它在我不单击按钮的情况下触发。那么我在这里做错了什么?
编辑:
这是 load_file 事件:
def load_file(area):
fname = askopenfilename(filetypes=(("TIF", "*.tif;*.tiff"),
("GIF", "*.gif"),
("JPEG", "*.jpg") ))
if fname:
fname = fname.replace("/", "\\")
print(fname)
Images.path = fname
import_file(fname, area)
else:
print "Could not open file ", fname
return fname
最佳答案
在下一行中,代码没有load_file
,而是调用load_file
并绑定(bind)函数调用的返回值。
abtn = Button(self, text="Open", command=load_file(area))
使用 labmda
将其替换为函数对象:
abtn = Button(self, text="Open", command=lambda: load_file(area))
关于python - Tkinter 按钮事件在加载时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20933639/