gpt4 book ai didi

python - 创建 Python 按钮保存编辑的文件

转载 作者:太空宇宙 更新时间:2023-11-03 17:46:53 25 4
gpt4 key购买 nike

我是 tkinter 的新手,想知道是否有人可以为我指出正确的方向。我想知道如何在没有 saveasdialog 的情况下覆盖以前保存的文件,就像如何实现实际的保存功能一样。我目前正在使用它为我的项目保存一个包含不同点的 .txt 文件。另存为功能有效。我是否必须找到该目录并以某种方式更改它?有没有更简单的方法来做到这一点?这是我迄今为止保存和保存的内容:

def saveFile(self):
method = self.method.current()
try:
with open(self.f,'w') as outputFile:
if(method==0):
method.write()
except AttributeError:
self.save_as

def saveFileAs(self):

f = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
method = self.method.current()
#used to write to .txt file and does save
if(method == 0):
# f.write() to save to .txtfile

最佳答案

如果您想要一个默默地覆盖当前文件的保存功能,基本要做的就是保存对用户选择的文件名/位置的引用,然后下次保存时您可以重复使用它而不是询问为了一个新的。下面的代码(取 self 的程序)有一个“普通”保存函数,它检查记录中是否有保存文件名,然后使用它(如果存在)或转到“另存为”函数。普通版本恰好有一个返回值,以便它可以与程序中其他位置的加载(打开)函数交互(询问用户是否在加载新文件之前保存未保存的工作)。 p>

def save_plain(self, *args):
"""
A plain save function. If there's no preexisting file name,
uses save_as() instead.
Parameter:
*args: may include an event
"""
if self.savename: # if there's a name
self.save(self.savename) # then use it
elif self.save_as(): # else, use save_as instead
return True # successful save returns True
return False # else, return False

def save_as(self, *args):
"""
A save as function, which asks for a name and only retains it if it was given
(canceling makes empty string, which isn't saved).
Parameter:
*args: may include an event
"""
temp = filedialog.asksaveasfilename(defaultextension=".txt", \
filetypes=(('Text files', '.txt'),('All files', '.*'))) # ask for a name
if temp: # if we got one,
self.savename = temp # retain it
self.save(temp) # and pass it to save()
return True
return False

def save(self, filename):
"""
Does the actual saving business of writing a file with the given name.
Parameter:
filename (string): the name of the file to write
"""
try: # write the movelist to a file with the specified name
with open(filename, 'w', encoding = 'utf-8-sig') as output:
for item in self.movelist:
output.write(item + "\n")
self.unsaved_changes = False # they just saved, so there are no unsaved changes
except: # if that doesn't work for some reason, say so
messagebox.showerror(title="Error", \
message="Error saving file. Ensure that there is room and you have write permission.")

关于python - 创建 Python 按钮保存编辑的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com