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

标签 python python-2.7 tkinter

使用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/

相关文章:

python - 在 Python 中优化两个矩阵的直方图距离度量

python将html文件打印到默认打印机

python - 按下按钮后多次更改 tkinter 输入小部件

python - AttributeError: 'Application' 对象没有属性 'tk'

python - Pygame2exe 字体相关的运行时错误

python - Popen 与冲突的可执行文件/路径

python - 如何使用 shell 命令将目录作为参数传递给 python 脚本?

python - 如何使用Python生成器

python - 继承一个补丁类

python - 对 root 与 self.root 以及 __init__ 的使用感到困惑。也与定义和类混淆