使用tkinter.filedialog.askdirectory()时有一个预加载的目录



我有以下代码:

导入:

from tkinter import *
from tkinter.filedialog import askopenfilename, askdirectory

main:

master = Tk()
Label(master, text="Output dir").grid(row=1, column=0 ,sticky=W)
with open('{}\resources\last_saved_dir.config'.format(path_of_main_project), 'r') as saved_dir:
last_dir = saved_dir.read().replace('n', '')
entry_dir=Entry(master, text=last_dir, width=50)
entry_dir.grid(row=1, column=1, sticky=W, padx=5)
Button(master, text="Browse...", width=10, command=lambda:get_ouput_directory(entry_dir)).grid(row=1, column=2, sticky=W)
# The following part is after directory is chosen, runs the rest of the program. 
# Not important for my question, just showing that I run and close my loop.
Button(master, text="Ok",     command=run_and_close, width=10).grid(row=3, column=1, sticky=E, padx=5)
Button(master, text="Cancel", command=close, width=10).grid(row=3, column=2, sticky=W)
master.bind('<Return>', run_and_close)
master.bind('<Escape>', close)
mainloop()

这将创建一个gui窗口,提示用户输入一个目录,其中包含文本Output dir,然后是一个打开的输入窗口,其中包含Browse按钮以加载目录

以下是get_ouput_directory()功能:

def get_ouput_directory(directory_entry):
dir_name = askdirectory(title = "SiteConverter output directory")
directory_entry.delete(0,END)
directory_entry.insert(0,dir_name)
with open('{}\resources\last_saved_dir.config'.format(path_of_main_project), 'w') as saved_dir:
saved_dir.write(dir_name)

想法是:

  1. 用户第一次运行时,输入窗口为空,用户将浏览一个目录,然后将其保存在名为last_saved_dir.config的文件中的某个文件夹中
  2. 第二次用户运行程序时,程序会读取该文件并在窗口中加载目录,这样,如果目录不变,用户就不必每次手动输入

请注意,程序不会从第二次运行开始读取文件,它会一直读取,但如果用户是第一次运行,第一次将是一个不需要的目录或为空。然而,每次运行脚本时,即使最后一个目录保存在last_saved_dir.config中,条目窗口也是空白的。当我在entry_dir=Entry(master, text=last_dir, width=50)之前添加print(last_dir)时,最后一个目录被正确读取,并且类型是<class 'str'>,这应该适合text= ...

我真的不确定条目的text=选项有什么作用,因为它在任何引用中都没有提到。要在条目中放入文本,请使用.insert()方法:

entry_dir.insert(END, last_dir)

然后,要始终打开条目中当前文件夹所在的askdirectory窗口,请使用

dir_name = askdirectory(title = "SiteConverter output directory", initialdir=directory_entry.get())

根据Bryan Oakley的评论,Tkinter接受选项名称的缩写,只要它们是唯一的。Entry小部件没有text选项,但它有一个textvariable选项,所以这是您在设置text=...时设置的选项。这就意味着,如果你要使用它,你不应该给它一个字符串对象,而是一个StingVar对象。对于这个特定的例子,没有它你就很好。

相关内容

最新更新