尝试制作带有“打开文件”按钮的 GUI。当我运行下面显示的代码时,打开文件对话框会立即打开,而不是当我按下按钮时。为什么?有没有一种不涉及使用类的简单方法来解决这个问题? (我目前对类(class)一无所知,并且正在从事一个时间紧迫的项目)
from tkinter import *
interface = Tk()
def openfile():
return filedialog.askopenfilename()
button = ttk.Button(interface, text = "Open", command = openfile())
button.grid(column = 1, row = 1)
interface.mainloop()
最佳答案
代码正在传递 openfile
函数调用的返回值,而不是函数本身。通过删除导致调用的尾随 ()
来传递函数本身。
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
interface = Tk()
def openfile():
return filedialog.askopenfilename()
button = ttk.Button(interface, text="Open", command=openfile) # <------
button.grid(column=1, row=1)
interface.mainloop()
关于python - 在 tkinter 中打开文件的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26607268/