首页 > 解决方案 > 从 tkinter filedialog 返回文件的文件路径

问题描述

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

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

我目前收到的错误是:

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

标签: pythontkinter

解决方案


试试这个

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


推荐阅读