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

2024-04-25 10:12:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的图形用户界面的全部思想是: 1几乎没有枪托 2有地址栏和文件的完整地址

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

我做了一些测试,但是当检查检索到的值时,我没有得到任何结果。在

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界面上,而不是将文件路径保存在任何变量中:

^{pr2}$

预期结果:https://imgur.com/a/NbiOPzG-不幸的是,我还不能发布图片,所以上传了一张到imgur上


Tags: 文件path代码路径tkinter地址xlsx图形用户界面
1条回答
网友
1楼 · 发布于 2024-04-25 10:12:17

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

Update

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

Note: I added a comment to point you to where the full file path is stored, in my example it's 'path' & 'path1'.

相关问题 更多 >