python - 在 tkinter 中打开文件的最简单方法

标签 python user-interface python-3.x tkinter

尝试制作带有“打开文件”按钮的 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/

相关文章:

Python/Tkinter : Using custom mouse cursors under Windows?

python - PyQT 全屏问题

python - wand - 文本换行 - 基于图像文件大小

python - flask 多处理

python - 如何在 Mac 上构建 wxFormBuilder 3.x

c++ - QTableView : how to select data?

c# - Winforms Treeview 节点工具提示自定义

python - 在python中生成随机句子

python - 如何为python应用创建多阶段dockerfile?

灯泡对象初始化方法中 fget 参数的 Python 灯泡框架示例