使用tkinter保存word文档的备份副本



我创建了一个tkinter GUI,它允许分析选定的Word文档。用户可以通过按下上传按钮来选择要分析的文件。

在开始分析之前,我想备份所选的文档。为了实现这一点,我尝试实现一个使用tkinter的asksaveasfile功能的函数(也可以通过按下上传按钮来执行(。这在一定程度上起作用,因为在用户使用askopenfile生成的对话框选择文件后,它会弹出另存为文件对话框。

但是,我无法将所选文件的名称传递给此函数(file_save_as(((,因此我可以备份该文件。我想知道如何用新文件名保存所选文档的副本(通过在原始名称中添加"_backup"(,而无需手动键入。例如,如果所选文档的标题为"myfile.docx",则应调用备份"myfile_backup.docx"。此文件重命名应自动完成

任何形式的帮助都将不胜感激。如果有任何关于代码的问题,请询问。

上传按钮的代码如下所示:

# upload button settings
upload_btn = tk.Button(root, command=lambda: [file_open(), file_save_as()])
upload_btn.configure(background="blue", font="{Arial} 16", text="Upload")
upload_btn.place(anchor="nw", relheight="0.10", relwidth="0.15", relx="0.10", rely="0.10", x="0", y="0") 

打开文件的函数代码如下所示(仅供参考,返回的变量"filename"包含所选文档的文件路径(:

# function to open a Word document using file explorer
def file_open():
upload_btn.configure(text="waiting...")
file = askopenfile(parent=root, mode='r', title="Choose a file", filetypes=[(".docx file", "*.docx")])
upload_btn.configure(text="Upload")
global filename
filename = file.name
file_label.configure(text="Chosen File: " + filename)
return filename

备份文件的功能代码如下所示:

def file_save_as():
copy_file = asksaveasfile(parent=root, mode='r', title="Backup chosen file", filetypes=[("Word file", "*.docx")])

如果您想将原始文件的副本保存到选定的文件夹中,最好使用askdirectory()而不是asksaveasfile(),然后以编程方式构造输出文件名,并使用shutil.copy2()备份原始文件:

...
from tkinter.filedialog import askdirectory
import pathlib
import shutil
...
def file_save_as():
folder = askdirectory(title="Choose backup folder")
if folder:
# filename is the selected file in file_open()
src = pathlib.Path(filename)
# src.stem is the filename without the directories and file extension parts
# src.suffix is the file extension, i.e. ".docx"
dst = pathlib.Path(folder) / f'{src.stem}_backup{src.suffix}'
# copy the source file to destination file using shutil.copy2()
shutil.copy2(src, dst)
...

最新更新