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

时间:2020-04-19 23:14:40

标签: python tkinter filepath

我正在使用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()

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

2 个答案:

答案 0 :(得分:1)

使用全局变量:

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)

关闭窗口后,您将获得file_path。

答案 1 :(得分:1)

您可以在file_path中将get_file_path声明为全局变量

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()

然后您可以从脚本中的任何位置访问该变量

------编辑------ 根据您在评论中所说,我说您可以使用tkinter.StringVar保存文件路径,然后稍后在调用count_frames作为参数时访问它。

它可以通过以下方式实现:

from tkinter import *
from tkinter import filedialog

file_path_var = StringVar()

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")))
    file_path_var.set(file_path) #setting the variable to the value from file path
    #Now the file_path can be acessed from inside the function and outside
    file_path_var.get() # will return the value stored in file_path_var
    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()
# will also return the value saved in file_path_var
file_path_var.get()
window.mainloop()
print(file_path)

因此,现在无论您的count_frames函数在哪里,只要您首先选择了一个文件,您都应该能够这样做

count_frames(file_path_var.get())