python tkInter浏览文件夹按钮

时间:2017-04-20 09:49:53

标签: python python-3.x tkinter

我想使用tkinter创建一个浏览文件夹按钮,并将路径存储到变量中。到目前为止,我能够打印路径,但我无法将其存储在变量中。你能告诉我吗?

下面我附上我使用的代码。

from tkinter import filedialog
from tkinter import *

def browse_button():
    filename = filedialog.askdirectory()
    print(filename)
    return filename


root = Tk()
v = StringVar()
button2 = Button(text="Browse", command=browse_button).grid(row=0, column=3)

mainloop()

提前谢谢你!

1 个答案:

答案 0 :(得分:13)

以下是将目录路径存储为全局变量并使用它来填充Label的示例。

from tkinter import filedialog
from tkinter import *

def browse_button():
    # Allow user to select a directory and store it in global var
    # called folder_path
    global folder_path
    filename = filedialog.askdirectory()
    folder_path.set(filename)
    print(filename)


root = Tk()
folder_path = StringVar()
lbl1 = Label(master=root,textvariable=folder_path)
lbl1.grid(row=0, column=1)
button2 = Button(text="Browse", command=browse_button)
button2.grid(row=0, column=3)

mainloop()