如何在Python/Tkinter中使用浏览按钮显示文件路径

2 投票
2 回答
10113 浏览
提问于 2025-04-18 16:21

我在用Python和Tkinter做项目,想知道怎么把文件路径显示在“浏览”按钮旁边,但一直没找到办法。

这是我的代码:

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


  #~~~~~~~~~~~~~~~~~~~

请告诉我,用户选择文件后,怎么才能把文件路径显示在“浏览”按钮旁边,就像这个图片里那样。

提前谢谢你们!

2 个回答

0

这里有一个修改的内容,它修复了 file_path,也就是 StringVar() 的用法:

--- old.py      2016-08-10 18:22:16.203016340 +0200
+++ new.py      2016-08-10 18:24:59.115328029 +0200
@@ -4,7 +4,6 @@


 content = ''
-file_path = ''


 #~~~~ FUNCTIONS~~~~
@@ -16,7 +15,7 @@
   filename = askopenfilename()
   infile = open(filename, 'r')
   content = infile.read()
-  file_path = os.path.dirname(filename)
+  file_path.set(os.path.dirname(filename))
   return content

 def process_file(content):
@@ -40,7 +39,7 @@
 f2 = Frame(mf, width=600, height=250)
 f2.pack()

-file_path = StringVar
+file_path = StringVar(root)


 Label(f1,text="Select Your File (Only txt files)").grid(row=0, column=0, sticky='e')
4

首先,把这一行改成:

    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() 函数里,我们清空它,并添加文件路径的文本。

撰写回答