从tkinter filedialog返回文件的文件路径

时间:2019-04-12 19:54:02

标签: python tkinter

我正在尝试使用tkinter构建一个简单的GUI,允许用户使用文件浏览器窗口选择文件,这将是另一个python脚本的输入。我想要一个Entry小部件,该控件允许用户手动输入文件路径。如果用户决定从浏览器中选择文件而不是输入文件,我希望Entry小部件显示选定的文件路径。

下面的代码可以构建表单(我没有对小部件进行太多格式化)并显示文件对话框窗口。使用函数“ show_file_browser”,我可以返回整个文件路径。我遇到的问题是将该文件路径粘贴到Entry小部件中。

我当前收到的错误是:

NameError: name 'filepath' is not defined

这是从“ first_browser”函​​数引发的。因为“文件路径”是在“ init_window”函数中声明的,所以当我尝试在“ first_browser”中进行设置时,它是未定义的。除了将'filepath'设置为全局变量(我不确定是否可以解决问题)之外,还有没有简便的方法可以完成我尝试的任务?

import tkinter as tk
from tkinter import filedialog

class Window(tk.Frame):
    def __init__(self, master = None):
        tk.Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def init_window(self):
        self.master.title("Form Title")
        self.pack(fill = 'both', expand = 1)

        filepath = tk.StringVar()

        quitButton = tk.Button(self, text = 'Quit',
                               command = self.close_window)
        quitButton.place(x = 0, y = 0)

        browseButton = tk.Button(self, text = 'Browse',
                                 command = self.first_browser)
        browseButton.place(x = 0, y = 30)

        filepathText = tk.Entry(self, textvariable = filepath)
        filepathText.pack()

    def close_window(self):
        form.destroy()

    def show_file_browser(self):
        self.filename = filedialog.askopenfilename()
        return self.filename

    def first_browser(self):
        filepath.set = self.show_file_browser()

form = tk.Tk()
form.geometry("250x250")
form.resizable(0, 0)

app = Window(form)

form.mainloop()

2 个答案:

答案 0 :(得分:1)

尝试一下

class Window(tk.Frame):
    def __init__(self, master = None):
        tk.Frame.__init__(self, master)
        self.master = master
        self.init_window()


    def init_window(self):
        self.master.title("Form Title")
        self.pack(fill = 'both', expand = 1)

        self.filepath = tk.StringVar()

        quitButton = tk.Button(self, text = 'Quit',
                               command = self.close_window)
        quitButton.place(x = 0, y = 0)

        browseButton = tk.Button(self, text = 'Browse',
                                 command = self.first_browser)
        browseButton.place(x = 0, y = 30)

        filepathText = tk.Entry(self, textvariable = self.filepath)
        filepathText.pack()

    def close_window(self):
        form.destroy()

    def show_file_browser(self):
        self.filename = filedialog.askopenfilename()
        return self.filename

    def first_browser(self):
        file = self.show_file_browser()
        self.filepath.set(file)

要在类内创建"global" variable,必须在变量名称前添加self.。 在您的代码中,您在first_browser(self)函数内部编写了代码 filepath.set = self.show_file_browser(),但是您不能执行此操作,必须先获取self.show_file_browser()返回的值,然后执行value=self.show_file_browser(),然后再将输入变量设置为该值

答案 1 :(得分:0)

<块引用>

“如果用户决定从浏览器中选择文件而不是输入文件,我希望 Entry 小部件显示选定的文件路径。”

此问题的解决方法如下: 您可以根据需要将代码实施到您的项目中。

from tkinter import messagebox
from tkinter import filedialog

def fileNameToEntry():

      files = [('All Files', '*.*'), 
             ('Python Files', '*.py'),
             ('Text Document', '*.txt')]
      filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = files,
                                          defaultextension = files)
      filename = filename.strip()

#User select cancel
      if (len(filename) == 0):
         messagebox.showinfo("show info", "you must select a file")       
         return
#selection go to Entry widget
      else:
         myStrVar.set(filename)
      
root = Tk()
root.title("select and show file path in Entry widget")
lblFileName  = Label(root, text = "Selected File Name", width = 24)
lblFileName.grid(padx = 3, pady = 5, row = 0, column = 0)

#make global variable to access anywhere
global myStrVar
myStrVar = StringVar()
txtFileName  = Entry(root, textvariable = myStrVar, width = 60, font = ('bold'))
txtFileName.grid(padx = 3, pady = 5, row = 0, column = 1)
btnGetFile = Button(root, text = "Get File Name", width = 15,
    command = fileNameToEntry)
btnGetFile.grid(padx = 5, pady = 5, row = 1, column = 0)
root.mainloop()

Output Window