繁体   English   中英

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

[英]Return filepath of file from tkinter filedialog

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

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

我目前收到的错误是:

NameError: name 'filepath' is not defined

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

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

试试这个

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()之后您可以将入口变量设置为该值

“如果用户决定从浏览器中选择文件而不是输入文件,我希望 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()

输出窗口

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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