如何使用Python Tkinter在对话框中选择后检索文件名



请在使用 tkinter 选择一个变量后告知如何将文件的完整路径检索到变量中

我的 GUI 的整个想法是:1.对接少2.具有带有文件完整地址的地址栏

用户单击按钮并选择文件后>>文件的路径将显示在地址栏中,并存储在单独的变量中,以供以后在代码中使用

我已经做了一些测试,但是在检查检索到的值时 - 我得到 None。

def file_picker():
    """Pick enova .xlsx file"""
    path = filedialog.askopenfilename(filetypes=(('Excel Documents', '*.xlsx'), ('All Files', '*.*')))
    return path
file_button = tkinter.Button(root, text='Users File', width=20, height=3, 
bg='white', command=custom_functions.file_picker).place(x=30, y=50)

除了我找到另一个代码片段的形式,但这只是将行捕获到 GUI 界面上,而不是将文件路径保存在任何变量中:

def browsefunc():
    filename = filedialog.askopenfilename()
    pathlabel.config(text=filename)
    print(pathlabel)

browsebutton = tkinter.Button(root, text="Browse", command=browsefunc).pack()
pathlabel = tkinter.Label(root).pack()

预期结果: https://i.stack.imgur.com/c9pcz.jpg - 不幸的是,我还不能发布图像,所以将图像上传到 imgur

要使用 Tkinter 捕获文件的完整路径,您可以执行以下操作。您的完整文件路径的输出将根据您在原始帖子中的要求显示在"输入"字段/地址栏中。

更新

import tkinter
from tkinter import ttk, StringVar
from tkinter.filedialog import askopenfilename
class GUI:
    def __init__(self, window): 
        # 'StringVar()' is used to get the instance of input field
        self.input_text = StringVar()
        self.input_text1 = StringVar()
        self.path = ''
        self.path1 = ''
        window.title("Request Notifier")
        window.resizable(0, 0) # this prevents from resizing the window
        window.geometry("700x300")
        ttk.Button(window, text = "Users File", command = lambda: self.set_path_users_field()).grid(row = 0, ipadx=5, ipady=15) # this is placed in 0 0
        ttk.Entry(window, textvariable = self.input_text, width = 70).grid( row = 0, column = 1, ipadx=1, ipady=1) # this is placed in 0 1
        ttk.Button(window, text = "Enova File", command = lambda: self.set_path_Enova_field()).grid(row = 1, ipadx=5, ipady=15) # this is placed in 0 0
        ttk.Entry(window, textvariable = self.input_text1, width = 70).grid( row = 1, column = 1, ipadx=1, ipady=1) # this is placed in 0 1
        ttk.Button(window, text = "Send Notifications").grid(row = 2, ipadx=5, ipady=15) # this is placed in 0 0
    def set_path_users_field(self):
        self.path = askopenfilename() 
        self.input_text.set(self.path)
    def set_path_Enova_field(self):
        self.path1 = askopenfilename()
        self.input_text1.set(self.path1)
    def get_user_path(self): 
        """ Function provides the Users full file path."""
        return self.path
    def get_enova_path1(self):
        """Function provides the Enova full file path."""
        return self.path1

if __name__ == '__main__':
    window = tkinter.Tk()
    gui = GUI(window)
    window.mainloop()
    # Extracting the full file path for re-use. Two ways to accomplish this task is below. 
    print(gui.path, 'n', gui.path1) 
    print(gui.get_user_path(), 'n', gui.get_enova_path1())

注意:我添加了一个注释来指向存储完整文件路径的位置,在我的示例中它是"path"和"path1"。

最新更新