Tkinter文件对话框结合了保存和加载对话框



我有一个输入小部件,用户可以在其中键入文件位置,下面有一个"保存"按钮和一个"加载"按钮。根据单击的按钮,在输入小部件中指定的文件将打开以进行写入或读取。

这一切都很好用。

现在我想添加一个"浏览"按钮,用户可以点击它打开一个文件对话框来选择一个文件。选择文件后,文件名将复制到条目中。从那时起,保存和加载按钮应该可以正常工作。

然而,我不知道如何让文件对话框既能读取文件又能写入文件。我不能使用tkFileDialog.asksaveasfilename,因为如果一个文件已经存在(如果用户打算"加载",它应该存在),而tkFileDialog.askloadasfilename函数不允许用户选择一个还不存在的文件(如果用户想"保存",也应该可以),这会向用户抱怨。

是否可以创建一个既不显示这两种功能的对话框?

这就是您想要的:

from tkinter import *
from tkinter.filedialog import *
root = Tk()
root.title("Save and Load")
root.geometry("600x500-400+50")
def importFiles():
    try:
        filenames = askopenfilenames()
        global file
        for file in filenames:
            fileList.insert(END, file)
    except:
        pass
def removeFiles():
    try:
        fileList.delete(fileList.curselection())
    except:
        pass
def openFile():
    try:
        text.delete(END)
        fob = open(file, 'r')
        text.insert(0.0, fob.read())
    except:
        pass
def saveFile():
    try:
        fob = open(file, 'w')
        fob.write(text.get(0.0, 'end-1c'))
        fob.close()
    except:
        pass
listFrame = Frame(root)
listFrame.pack()
sby = Scrollbar(listFrame, orient='vertical')
sby.pack(side=RIGHT, fill=Y)
fileList = Listbox(listFrame, width=100, height=5, yscrollcommand=sby.set)
fileList.pack()
sby.config(command=fileList.yview)
buttonFrame = Frame(root)
buttonFrame.pack()
importButton = Button(buttonFrame, text="Import", command=importFiles)
importButton.pack(side=LEFT)
removeButton = Button(buttonFrame, text="Remove", command=removeFiles)
removeButton.pack(side=LEFT)
openButton = Button(buttonFrame, text="Open", command=openFile)
openButton.pack(side=LEFT)
saveButton = Button(buttonFrame, text="Save", command=saveFile)
saveButton.pack(side=LEFT)
text = Text(root)
text.pack()
root.mainloop()

"我想要一个返回文件名的对话框,该文件名可用于保存和加载。"
您可以使用对话框窗口导入文件名;从列表中删除所选文件名(附加功能);打开您选择的文件;最后,编写并保存它们
附言:我的代码中可能有一些错误,但我认为算法可以满足问题的要求。

最新更新