python tkInter浏览文件夹按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43516019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:09:32  来源:igfitidea点击:

python tkInter browse folder button

pythonpython-3.xtkinter

提问by Giorgos Synetos

I would like to make a browse folder button using tkinter and to store the path into a variable. So far i am able to print the path but i am not able to store it in a variable. Can you please advise?

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

Below i attach the code that i use.

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

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

Thanks you in advance!

提前谢谢你!

回答by scotty3785

Here is an example of storing the directory path as a global variable and using that to populate a 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()