提取文本并写入新的 Word 文件

Extract text and write to new Word file

我正在尝试制作一个带有 2 个按钮的 GUI Tkinter,每个按钮用于:提取段落(1、2、3 随便什么)并复制到新的文本文件(Pyhton 3.8,PyCharm(Windows 10, OS). 但问题是,它提取,复制到新文件,但不添加,它只使 extracts/copy 到新文件,一个按钮而不是两个其中

这是代码(请记住,我完全是业余爱好者,在 Python 中只激活了 2 周:D)

from tkinter import *

import docx
from docx import Document

doc = docx.Document("C:/Users/Dorian/Desktop/Descriere/1/texte_aparate_de_aer_conditionat.docx")

def intro_text():

    document = Document()

   single_para1 = doc.paragraphs[2]
    single_para2 = doc.paragraphs[4]

    document.add_paragraph(single_para1.text)
    document.add_paragraph(single_para2.text)
    document.save('C:/Users/Dorian/Desktop/Descriere/1/txt.docx')

  def specs():

    document = Document()

    single_para3 = doc.paragraphs[6]
    single_para4 = doc.paragraphs[16]

    document.add_paragraph(single_para3.text)
    document.add_paragraph(single_para4.text)
    document.save('C:/Users/Dorian/Desktop/Descriere/1/txt.docx')

main=Tk()
main.title('Descriere Aparate de Aer Conditionat')
main.geometry('400x100')

GUIFrame=Frame(main)
GUIFrame.grid(row=1, column=1, sticky=W)

Button(GUIFrame, text="Pentru cele cu Wi-Fi", width=35, command=intro_text).grid(row=1, column=1, sticky=W)
Button(GUIFrame, text="Eficienta", width=35, command=specs).grid(row=3, column=1, sticky=W)

main.mainloop()

谢谢!

如果我正确理解你的问题,你想在新文档中添加段落。据我所知,这两个按钮都会创建一个新文档,但它们会以相同的名称保存它。 因此,每次按下按钮时,您都会继续覆盖文档。

您应该创建单独的函数:一个用于创建新文档,然后两个用于向该文档添加段落,最后一个函数用于保存文档。