首页 > 解决方案 > 当用户编写名字和姓氏框时,我希望它使用 tkinter 和 python-docx 在单元格中打印它,我该怎么做?

问题描述

我有一个使用 docx-python 生成 word 文档的程序,我想使用 tkinter 设计一个 GUI。那么,当我输入,例如,我想在表格中的 word 文档中打印它的名称时,我该如何为这样的东西编码?

root = Tk()
root.geometry('500x500')
root.title("Registration")

label_1 = Label(root, text="FullName",width=20,font=("bold", 10))
label_1.place(x=80,y=130)
entry_1 = Entry(root)
entry_1.place(x=240,y=130)

root.mainloop()
document = Document()
t = document.add_table(rows=3, cols=2, style='TableGrid')
for row in t.rows:
    row.height = Inches(0.4)
cell = t.cell(0, 0)
cellp=cell.paragraphs[0]
#here where I want the name get print it
cellp.text='Name : '
cellp.add_run(FullName)

标签: python

解决方案


首先,您需要向 GUI 添加按钮,因为没有root.mainloop()事件之后将不会执行任何操作。所以,让我们添加一个按钮:

add_btn = Button(root)
add_btn["text"] = "Add name"
add_btn["command"] = add_to_document
add_btn.place(x=240,y=160)

在上面的示例中,只要单击“添加名称” ,add_btn就会调用函数。add_to_document

这是您需要拥有文档逻辑的地方。

这是一个工作示例,其中包含一个按钮和一个在按下此按钮时打印文本字段内容的函数。

def add_to_document():
    print("Adding " + entry_1.get())

from tkinter import *
root = Tk()
root.geometry('500x500')
root.title("Registration")

label_1 = Label(root, text="FullName",width=20,font=("bold", 10))
label_1.place(x=80,y=130)
entry_1 = Entry(root)
entry_1.place(x=240,y=130)

# Adding a button
add_btn = Button(root)
add_btn["text"] = "Add name"
add_btn["command"] = add_to_document
add_btn.place(x=240,y=160)

root.mainloop()

还有其他方法可以做到这一点,也有更好的方法来组织事情。我建议阅读https://docs.python.org/3/library/tkinter.html

他们有一个“hello world”示例,您可以从中汲取灵感。https://docs.python.org/3/library/tkinter.html#a-simple-hello-world-program


推荐阅读