使用Python和Tkinter,我一直试图找出在浏览按钮旁边显示file_path的方法,但无法做到这一点。
这是我的代码:
import os
from tkFileDialog import askopenfilename
from Tkinter import *
content = ''
file_path = ''
#~~~~ FUNCTIONS~~~~
def open_file():
global content
global file_path
filename = askopenfilename()
infile = open(filename, 'r')
content = infile.read()
file_path = os.path.dirname(filename)
return content
def process_file(content):
print content
#~~~~~~~~~~~~~~~~~~~
#~~~~~~ GUI ~~~~~~~~
root = Tk()
root.title('Urdu Mehfil Ginti Converter')
root.geometry("598x120+250+100")
mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack()
file_path = StringVar
Label(f1,text="Select Your File (Only txt files)").grid(row=0, column=0, sticky='e')
Entry(f1, width=50, textvariable=file_path).grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse", command=open_file).grid(row=0, column=27, sticky='ew', padx=8, pady=4)
Button(f2, text="Process Now", width=32, command=lambda: process_file(content)).grid(sticky='ew', padx=10, pady=10)
root.mainloop()
#~~~~~~~~~~~~~~~~~~~
请指导我如何在用户选择文件后显示文件路径以及“浏览按钮”按钮,如image所示.
提前致谢!
最佳答案
首先,更改此行:
Entry(f1, width=50, textvariable=file_path).grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
对此:
entry = Entry(f1, width=50, textvariable=file_path)
entry.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
然后,在 open_file()
函数中,在 return
之前添加这两行:
entry.delete(0, END)
entry.insert(0, file_path)
说明:
首先,我们给条目命名,以便可以对其进行修改。
然后,在 open_file()
函数中,我们清除它并添加文件路径的文本。
关于python - 如何在 Python/Tkinter 中使用浏览按钮显示文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25175613/