在使用tkinter选择文件后,请提供有关如何将文件的完整路径检索到变量中的建议
我的GUI的整个想法是: 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界面上,尽管没有将文件路径保存在任何变量中:
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://imgur.com/a/NbiOPzG-很遗憾,我无法发布图像,因此已将其上传到imgur
答案 0 :(得分:0)
要使用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”。