我有一个通过askdirectory打开文件夹的应用程序并显示在GUI的输入框中,我的问题是如何将打开的文件夹保存到文件并在程序重新打开时再次调用它?
我的代码:
import os
from tkinter import *
from tkinter import filedialog
inPut_dir = ''
def inPut():
opendir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
inPut_dir = StringVar()
inPut_dir = os.path.abspath(opendir)
entry.delete(0, END)
entry.insert(0, inPut_dir)
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, textvariable=inPut_dir)
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)
ButtonC = Button(frameright, text="Cancel").grid(row=5, column=15)
frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)
root.mainloop()
答案 0 :(得分:0)
您可以使用open()函数。
您可以定义包装函数,如:
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]$(parse_git_branch)\n\$ '
将字符串变量def save_to_file(filename, string):
with open(filename,'w') as out_file:
out_file.write(string)
def read_from_file(filename):
_dir = ''
with open(filename) as in_file:
_dir = in_file.read()
return _dir
保存(写入)到名为opendir
的文件中:
opendir.txt
稍后阅读文件:
FILENAME = 'opendir.txt'
save_to_file(opendir, FILENAME)
答案 1 :(得分:0)
试试这个:
import os
from tkinter import *
from tkinter import filedialog
def inPut():
opendir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
inPut_dir.set (os.path.abspath (opendir))
root = Tk()
root.geometry("640x240")
root.title("Settings")
frametop = Frame(root)
framebottom = Frame(root)
frameright = Frame(framebottom)
inPut_dir = StringVar ()
text = Label(frametop, text="Input Folder").grid(row=5, column=2)
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
if os.path.isfile ("path.txt"):
with open ("path.txt") as f: inPut_dir.set (f.read ())
else: inPut_dir.set ("")
ButtonA = Button(frametop, text="Change", command=inPut).grid(row=5, column=28)
ButtonB = Button(frameright, text="OK").grid(row=5, column=20, padx=10)
ButtonC = Button(frameright, text="Cancel").grid(row=5, column=15)
frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)
root.mainloop ()
with open ("path.txt", "w") as f: f.write (inPut_dir.get ())
编辑:
如果您对选择多个目录感兴趣,可以查看另一个stack overflow
问题的this链接。