我想在某个时候弹出一条消息,要求用户选择一个文件,然后显示所选文件的路径。之后,在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
被分配和在一行检查!
额外供参考
所有的几何管理器方法(pack
、place
和grid
)都返回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