使用“浏览”按钮在 Tkinter 中显示文件的路径 - Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38976790/
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
Display Path of a file in Tkinter using "browse" Button - Python
提问by Jindil
I have been reading through several posts regarding to Browse button issues in Tkinter but I could not find my answer.
我一直在阅读有关 Tkinter 中浏览按钮问题的几篇文章,但找不到答案。
So I have wrote this code to get a directory path when clicking the browse button, and displaying this path in an entry field. It woks partly : a file browser window directly pops up when I run the script. I indeed get the path in the entry field but if I want then to change the folder using my Browse button it does not work.
因此,我编写了此代码以在单击浏览按钮时获取目录路径,并在输入字段中显示此路径。它部分起作用:当我运行脚本时,会直接弹出一个文件浏览器窗口。我确实在输入字段中获得了路径,但是如果我想使用浏览按钮更改文件夹,则它不起作用。
I dont want to have the browser poping up right from the start but only when I click on Browse ! Thanks for your answers
我不想让浏览器从一开始就弹出,但只有当我点击浏览时!谢谢你的回答
from Tkinter import *
from tkFileDialog import askdirectory
window = Tk() # user input window
MyText= StringVar()
def DisplayDir(Var):
feedback = askdirectory()
Var.set(feedback)
Button(window, text='Browse', command=DisplayDir(MyText)).pack()
Entry(window, textvariable = MyText).pack()
Button(window, text='OK', command=window.destroy).pack()
mainloop()
回答by Parviz Karimli
This is so easy -- you need to assign the path to a variable and then print it out:
这很简单——您需要将路径分配给一个变量,然后将其打印出来:
from tkinter import *
root = Tk()
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
browsebutton = Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
pathlabel = Label(root)
pathlabel.pack()
P.S.:This is in Python 3. But the concept is same.
PS:这是在 Python 3 中。但概念是一样的。