You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyMuPDF与Tkinter时仅单个文本项可添加至PDF的问题求助

问题分析与解决:仅第一个输入框内容能写入PDF

核心问题

你代码里的关键错误是获取输入内容时没有对应到正确的输入框:

# 错误代码
text = text_entry.get()
text2 = text_entry.get()  # 此处应调用text_entry2.get()
text3 = text_entry.get()  # 此处应调用text_entry3.get()

不管用户在日期、职业输入框里填了什么,程序都只读取了姓名输入框的内容,后两个PDF位置写入的自然也是姓名框的内容(如果姓名框为空,那后两个位置就是空值)。

修正后的完整代码

把获取输入内容的三行改成对应输入框即可,同时补充了用户取消文件操作时的异常处理,避免程序报错:

import fitz  # PyMuPDF library
import tkinter as tk
from tkinter import filedialog

def add_text_to_pdf():
    # 选择PDF文件
    file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
    if not file_path:
        return
    pdf_document = fitz.open(file_path)

    # 加载单页PDF的第一页
    page = pdf_document.load_page(0)

    # 读取对应输入框的内容
    text = text_entry.get()
    text2 = text_entry2.get()
    text3 = text_entry3.get()

    # 定义文本插入位置
    text_rect = fitz.Rect(202, 626, 441, 647)
    text_rect2 = fitz.Rect(104, 667, 359, 685)
    text_rect3 = fitz.Rect(85, 711, 280, 726)

    # 插入文本到对应位置
    page.insert_textbox(text_rect, text)
    page.insert_textbox(text_rect2, text2)
    page.insert_textbox(text_rect3, text3)

    # 保存修改后的PDF
    output_file_path = filedialog.asksaveasfilename(defaultextension=".pdf", filetypes=[("PDF files", "*.pdf")])
    if not output_file_path:
        pdf_document.close()
        return
    pdf_document.save(output_file_path)
    pdf_document.close()

# 创建GUI界面
window = tk.Tk()
window.title("PDF Text Editor")

tk.Label(window, text="Name").pack()
text_entry = tk.Entry(window)
text_entry.pack()

tk.Label(window, text="Date").pack()
text_entry2 = tk.Entry(window)
text_entry2.pack()

tk.Label(window, text="Occupation").pack()
text_entry3 = tk.Entry(window)
text_entry3.pack()

# 添加操作按钮
add_text_button = tk.Button(window, text="Add Text to PDF", command=add_text_to_pdf)
add_text_button.pack()

window.mainloop()

内容的提问来源于stack exchange,提问作者dataguy2650

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 21:30:21