如何在 Python/Tkinter 中使用浏览按钮显示文件路径 [英] How to Show File Path with Browse Button in Python / Tkinter

查看:107
本文介绍了如何在 Python/Tkinter 中使用浏览按钮显示文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Python 和 Tkinter,我一直试图找出在浏览按钮旁边显示 file_path 的方法,但无法这样做.

Working with Python and Tkinter, I have been trying to find out the way to show the file_path beside the Browse Button but unable to do so.

这是我的代码:

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


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

请指导我如何在用户选择文件后显示文件路径和浏览按钮"按钮,如下所示 图像.

Kindly guide me as how I can show the file path along with the "Browse Button" button after the user selects the file as shown in this 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 之前添加这两行:

Then, in the open_file() function, add these two lines, just before the return:

entry.delete(0, END)
entry.insert(0, file_path)

<小时>

说明:首先,我们为条目命名,以便可以对其进行修改.然后,在 open_file() 函数中,我们清除它并为文件路径添加文本.


Explanation: First, we give the entry a name, so that it can be modified. Then, in the open_file() function we clear it and add the text for the file-path.

这篇关于如何在 Python/Tkinter 中使用浏览按钮显示文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆