【问题标题】:Tkinter file dialog combining save and load dialogsTkinter 文件对话框结合了保存和加载对话框
【发布时间】:2016-11-25 05:23:08
【问题描述】:

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

这一切都很好,花花公子。

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

但是,我不知道如何让文件对话框同时用于读取文件和写入。我不能使用tkFileDialog.asksaveasfilename 因为如果文件已经存在(如果用户打算“加载”,它应该)并且tkFileDialog.askloadasfilename 函数不允许用户选择一个尚不存在的文件(如果用户打算“保存”,也应该没问题)。

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

【问题讨论】:

  • 询问目录而不是文件名! stackoverflow.com/questions/11295917/…
  • 请求目录根本不允许您选择文件。 ("文件夹 C:\test.txt 无法使用,请选择其他文件夹。")
  • 如果要保存使用询问目录,请询问文件名。使用 2 个按钮 SAVELOAD 创建顶级窗口。这并不简单:如果文件被锁定(意味着打开),如果存在,如果覆盖等等......
  • 整点是我想要一个可以同时做这两件事的对话框。如果我想要你的建议,我会使用 asksaveasfilenameaskloadasfilename
  • 请在您的问题中添加一些代码。

标签: python tkinter


【解决方案1】:

这是你要找的吗:

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()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多