与Tkinter如何返回点击浏览按钮后的值?



我想在某个时候弹出一条消息,要求用户选择一个文件,然后显示所选文件的路径。之后,在GUI关闭后,我想在项目的其他部分使用路径信息。

from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
import os
win = Tk()
win.geometry("400x200")
def open_file():
file = filedialog.askopenfile(mode='r', filetypes=[('Exe Files', '*.exe')])
if file:
filepath = os.path.dirname(file.name)
Label(win, text="The File is located at : " + str(filepath), font=('Aerial 11')).pack()
return filepath
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13'))
label.pack(pady=10)
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)
win.mainloop()

我想在关闭GUI后使用文件路径的值。

EDIT

显然我忽略了这个问题最重要的部分:

我想在关闭GUI后使用文件路径的值

为了完成这一点,您必须将文件名写入类似文本文件的东西(或在GUI外部存储它的任何其他方式)。然后,无论您正在执行的哪个进程需要该文件路径,都可以从文件中读取它。

另一种选择是将filepath的值存储在系统环境变量中。这样,任何可以访问环境变量的进程都可以检索路径。


处理这个问题最简单的方法可能是全球化filepath变量。看起来你已经把其他的东西都设置好了。

filepath = ''  # declare the filepath variable, set to an empty string by default

def open_file():
global filepath  # let this function modify the value of 'filepath'

# 'file' is a reseved word in Python - it's best not to use it here
f = filedialog.askopenfile(mode='r', filetypes=[('Exe Files', '*.exe')])
if f:
filepath = os.path.dirname(f.name)
Label(win, text="The File is located at : " + str(filepath), font=('Aerial 11')).pack()
# no need to return the value as it's now stored in the 'filepath' global
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13'))
label.pack(pady=10)
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)

加分

如果你使用Python 3.8或更高版本,你可以使用assignment expression(又名,海象操作符:=)来进一步简化你的if语句

if f := filedialog.askopenfile(mode='r', filetypes=[('Exe Files', '*.exe')])
print(f)  # or whatever...

现在f被分配在一行检查!


额外供参考

所有的几何管理器方法(packplacegrid)都返回None。如果您打算以后在

中引用您的小部件,那么您最好将它们分别声明和将它们添加到窗口中。
# Avoid this!
my_btn = ttk.Button(win).pack()
print(my_btn)
>>> None
# Do this instead
my_btn = ttk.Button(win)
my_btn.pack()
print(my_btn)
>>> .!button

最新更新