简体   繁体   中英

Return filepath of file from tkinter filedialog

I am trying to build a simple GUI with tkinter that allows users to select a file using the a file browser window, which will be an input for another python script. I would like to have an Entry widget that allows the user to type in the file path manually. If the user decides to pick the file from the browser rather than typing it in, I would like the Entry widget to display the selected file path.

The code below can build the form (I haven't formatted the widgets much) and display the file dialog window. With the function 'show_file_browser', I am able to return the entire file path. The issue I am having is pasting that file path into the Entry widget.

The error I receive currently is:

NameError: name 'filepath' is not defined

This is raised from the 'first_browser' function. Because 'filepath' is declared in the 'init_window' function, it is undefined when I try to set it in 'first_browser'. Short of making 'filepath' a global variable (which I'm not sure would fix the problem) is there an easy way to complete the task I'm attempting?

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

Try with this

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)

for create a "global" variable inside a class you have to add self. before the variable name. In your code u wrote inside the first_browser(self) function filepath.set = self.show_file_browser() but you can't do this, before you have to take the value returned by self.show_file_browser() so doing this value=self.show_file_browser() and after you can set the entry variable to that value

"If the user decides to pick the file from the browser rather than typing it in, I would like the Entry widget to display the selected file path."

The solution for this issue is as follows: you can implement the code into your project as appropriate.

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

输出窗口

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM