任何人都可以幫忙,我是編碼新手,我試圖創建一個檔案生成器程式,通過使用 tkinter 條目小部件替換現有單詞檔案(通過路徑)中的占位符單詞(大括號中的單詞,例如:{{NAME}}),然后生成一個帶有新更改的新 word 檔案,但我無法讓條目小部件與字典一起使用(它使用字典使用 docxtemplate 將鍵交換為值)。簡單地說,我希望字典中的值是動態和變化基于用戶的輸入輸入,因此它可以與它的鍵交換,如果這有意義的話。我受到 youtube 上的這個視頻https://youtu.be/fziZXbeaegc的啟發。這里是一個基本代碼(注:i不要得到任何錯誤):
from pathlib import Path
from docxtpl import DocxTemplate
from tkinter import *
document_path = Path(__file__).parent / (r"C:\Users\Acer\Desktop\python\My name is.docx")
doc = DocxTemplate(document_path)
#define submit
def submit():
doc.render(swap)
doc.save(Path(__file__).parent / "generated_doc.docx")
#The app window
root = Tk()
#input field properties
entry=Entry(root,
font=("Arial",15))
entry.pack(side=LEFT)
swap={"NAME" : "Joe"}
#document generation button propeties
generate_button=Button(root,text="Generate",command=submit)
generate_button.pack(side=RIGHT)
root.mainloop()
uj5u.com熱心網友回復:
兩件事情。
首先,這可能是一個錯誤,因為第二部分已經是完整路徑。
document_path = Path(__file__).parent / (r"C:\Users\Acer\Desktop\python\My name is.docx")
那應該是:
document_path = Path(r"C:\Users\Acer\Desktop\python\My name is.docx")
其次,需要用Entry轉換前的內容修改字典。
def submit():
# The following line updates the dictionary.
swap["NAME"] = entry.get()
doc.render(swap)
doc.save(Path(__file__).parent / "generated_doc.docx")
和一個建議。不是硬編碼檔案名,而是使用filedialog.askopenfilename()按鈕回呼來獲取要處理的檔案的名稱,如下所示:
fn = filedialog.askopenfilename(
title='Word file to open',
parent=root,
defaultextension='.docx',
filetypes=(('Word files', '*.doc*'), ('all files', '*.*')),
)
回傳后,fn包含所選檔案的路徑。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/512045.html
