使用tkinter将文件路径保存在变量中

问题描述 投票:0回答:1

我正在使用tkinter来为我拥有的旧脚本创建GUI,但是我现在陷入困境。我想单击一个按钮以打开“搜索文件”窗口,选择一个特定文件并将其路径保存在变量中。我拥有的代码能够打开窗口,然后可以选择文件并显示其路径,但是我找不到将这种路径保存在变量中的方法。这就是我所拥有的:

from tkinter import *
from tkinter import filedialog

def get_file_path():
    # Open and return file path
    file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
    l1 = Label(window, text = "File path: " + file_path).pack()

window = Tk()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
window.mainloop()

有人知道这样做的好方法吗?

python tkinter filepath
1个回答
0
投票

使用全局变量:

from tkinter import *
from tkinter import filedialog

def get_file_path():
    global file_path
    # Open and return file path
    file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
    l1 = Label(window, text = "File path: " + file_path).pack()

window = Tk()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
window.mainloop()
print(file_path)

关闭窗口后,您将获得文件路径。

© www.soinside.com 2019 - 2024. All rights reserved.