美好的一天,
我正在使用tkinter filedialog选择一个文件夹,并在GUI上的条目中显示它?
这是我到目前为止的代码:
import os
from tkinter import *
from tkinter import filedialog
dir_path = ''
def inPut():
indir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
indir = str(indir)
dir_path = os.path.dirname(indir)
entry.delete(0, END)
entry.insert(0, dir_path)
return dir_path
root = Tk()
root.geometry("640x240")
root.title("Settings")
frametop = Frame(root)
framebottom = Frame(root)
frameright = Frame(framebottom)
text = Label(frametop, text="Input Folder").grid(row=5, column=2)
entry = Entry(frametop, width=50, text=dir_path)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
ButtonA = Button(frametop, text="Change", command=inPut).grid(row=5, column=28)
ButtonB = Button(frameright, text="OK").grid(row=5, column=20, padx=10)
frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)
root.mainloop()
当前,它仅返回d:/'
如何使其返回条目中的完整路径?
如何更改"/"到" "
下次我运行应用程序时,如何使该应用程序记住该文件夹?
请帮助!
要将其写入您的标签中,您需要对其进行引用。
多种可能性:
- 为您的GUI创建一个类,并使用
showdir
或将其作为实例变量绑定的文本变量 - 将您的呼叫的引用传递给
showdir
可用 - 全局
showdir
为什么要此订单?最不可行的。
如果您不知道如何从文件中写入或阅读,请在开始创建GUI之前先从Python教程开始。如果您不知道为什么在执行某些步骤时,"混淆了其他人的代码混淆,则没有任何意义。就像驾驶汽车而不知道交通是什么。
关于您的编辑:
您的代码现在确实可以正常工作,因为您无法直接访问该属性,因此您不会立即使用对条目进行写入访问。
-
return dir_path
完全过时。 - 您不会在
os.path.dirname(indir)
返回时获取文件夹 - 根据文档中的定义,父级目录的路径。如果您使用文件而不是目录dirname,则只要您使用目录,请使用os.path.abspath
。
os.path.dirname(路径(¶
返回路径名的目录名称。这是通过将路径传递到函数split((返回的对的第一个元素。