我在tkinter上遇到了这个问题。我想创建一个GUI来恢复通过askopenfilename选择的文件的路径和名称,然后将在后续代码中使用。我试过可能的选择,但我没有成功。我得到的最好的是跟随但不回报我需要的东西。谢谢你的帮助。
import tkinter as tk
from tkinter.filedialog import askopenfilename
class TkFileDialogExample(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
self.a=[]
tk.Button(self, text='askopenfilename', command=self.askopenfilename).pack()
def askopenfilename(self):
filename= askopenfilename()
self.a.append(filename)
return self.a
# MAIN PROGRAM
aa=[]
root = tk.Tk()
TkFileDialogExample(root).pack()
root.mainloop()
aa.append(TkFileDialogExample.askopenfilename)
print(aa)
答案 0 :(得分:0)
我认为一个例子在评论中会有所帮助
import tkinter as tk
from tkinter.filedialog import askopenfilename
filenames = []
def open_file():
filename = askopenfilename()
if filename:
filenames.append(filename)
root = tk.Tk()
tk.Button(root, text='Open File', command=open_file).pack()
root.mainloop()
print(filenames)
当您退出GUI时,您将获得一个列表,其中包含用户未单击取消的文件管理列表中所有有效打开的文件名。
答案 1 :(得分:0)
下面的代码创建一个GUI,其上有一个按钮,弹出一个askopenfilename对话框并将结果添加到列表中。 该按钮还向GUI添加一个标签,在其上显示askopenfilename对话框返回的文件路径。
import tkinter as tk
from tkinter.filedialog import askopenfilename
###Step 1: Create The App Frame
class AppFrame(tk.Frame):
def __init__(self, parent, *args, **kwargs):
###call the parent constructor
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
###Create button
btn = tk.Button(self, text='askopenfilename',command=self.askopenfilename)
btn.pack(pady=5)
def askopenfilename(self):
###ask filepath
filepath = askopenfilename()
###if you selected a file path
if filepath:
###add it to the filepath list
self.parent.filepaths.append(filepath)
###put it on the screen
lbl = tk.Label(self, text=filepath)
lbl.pack()
###Step 2: Creating The App
class App(tk.Tk):
def __init__(self, *args, **kwargs):
###call the parent constructor
tk.Tk.__init__(self, *args, **kwargs)
###create filepath list
self.filepaths = []
###show app frame
self.appFrame = AppFrame(self)
self.appFrame.pack(side="top",fill="both",expand=True)
###Step 3: Bootstrap the app
def main():
app = App()
app.mainloop()
if __name__ == '__main__':
main()