【问题标题】:Module's function auto running? [duplicate]模块功能自动运行? [复制]
【发布时间】:2016-12-25 14:58:10
【问题描述】:
我不明白为什么我调用的函数在我运行脚本时会在不按按钮的情况下运行。
import tkinter
from tkinter import filedialog
root = tkinter.Tk ()
root.title("fool")
root.geometry("300x300")
br = tkinter.Button(root, text ="Carica File", command = filedialog.askopenfile(mode="r"))
br.pack()
【问题讨论】:
标签:
python
python-3.x
tkinter
【解决方案1】:
现在,您正在传递调用的结果
filedialog.askopenfile(mode="r")
到command 参数。为了能够得到这个结果,该函数被执行并且您会立即看到对话框。您可能想要做的只是提供按下按钮时要调用的函数的名称,因此您可以将其定义为
def foo():
filedialog.askopenfile(mode="r")
并使用
command = foo
在Button 电话中。你在上面的代码中所做的对应于command = foo()(它执行函数),而不是command = foo。
如果你想在同一行中做所有事情,而不是定义额外的函数,你也可以使用 lambda 并编写:
command = lambda: filedialog.askopenfile(mode="r")