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

PySimpleGUI合同生成器点击按钮无输出问题求助

问题分析与修复方案

核心问题

  1. 标签页选中状态判断错误
    PySimpleGUI的TabGroup不会自动把标签名存入values字典,必须给TabGroup设置key,才能通过values[key]获取当前选中的标签标题。原代码里用values.get("Vendor Contract")永远返回None,导致两个分支都不会执行。

  2. 全局模板对象状态污染
    程序启动时就初始化了vendor_doc和gdpr_doc,第一次渲染后模板内容已经被修改,后续再调用render()会基于已修改的模板操作,导致输出异常或无输出。

  3. 提示弹窗缺失
    只有GDPR分支有保存成功弹窗,Vendor分支没有,且未处理异常分支的提示。


修复后的完整代码

import datetime
from pathlib import Path
import PySimpleGUI as sg
from docxtpl import DocxTemplate

# Initialize PySimpleGUI
sg.theme("Default1")

# Get the current date and date one week from today
today = datetime.datetime.today()
today_in_one_week = today + datetime.timedelta(days=7)

# Create the main layout with tabs for Vendor and GDPR contracts
main_layout = [
    [sg.TabGroup([
        [sg.Tab('Vendor Contract', [
            [sg.Text("Client name:"), sg.Input(key="CLIENT")],
            [sg.Text("Vendor Name:"), sg.Input(key="VENDOR")],
            [sg.Text("Amount:"), sg.Input(key="AMOUNT")],
            [sg.Text("Description1:"), sg.Input(key="LINE1")],
            [sg.Text("Description2:"), sg.Input(key="LINE2")]
        ])],
        [sg.Tab('GDPR Contract', [
            [sg.Text("Nume client:"), sg.Input(key="Nume")],
            [sg.Text("Cod Numeric Personal:"), sg.Input(key="Cod")]
        ])]
    ], key="-TABGROUP-")],  # 给TabGroup添加key,用于获取当前选中标签
    [sg.Button("Create Contract"), sg.Button("Exit")]
]

# Create the PySimpleGUI window
window = sg.Window("Contract Generator", main_layout)

while True:
    event, values = window.read()

    if event == sg.WIN_CLOSED or event == "Exit":
        break
    elif event == "Create Contract":
        # Add calculated fields to the dict
        values["TODAY"] = today.strftime("%Y-%m-%d")
        values["TODAY_IN_ONE_WEEK"] = today_in_one_week.strftime("%Y-%m-%d")

        current_tab = values["-TABGROUP-"]  # 获取当前选中的标签标题
        output_path = None
        success = False

        if current_tab == 'Vendor Contract':
            # 每次生成时重新加载模板,避免状态污染
            vendor_document_path = Path.cwd() / "vendor-contract.docx"
            vendor_doc = DocxTemplate(vendor_document_path)
            
            try:
                values["NONREFUNDABLE"] = round(float(values["AMOUNT"]) * 0.2, 2)
                vendor_doc.render(values)
                output_path = Path.cwd() / f"{values['VENDOR']}-contract.docx"
                vendor_doc.save(output_path)
                success = True
            except ValueError:
                sg.popup_error("金额输入无效,请输入数字")
            except Exception as e:
                sg.popup_error(f"保存文件出错: {str(e)}")

        elif current_tab == 'GDPR Contract':
            # 每次生成时重新加载模板
            gdpr_document_path = Path.cwd() / "gdpr.docx"
            gdpr_doc = DocxTemplate(gdpr_document_path)
            
            try:
                gdpr_doc.render(values)
                output_path = Path.cwd() / f"{values['Nume']}-gdpr.docx"
                gdpr_doc.save(output_path)
                success = True
            except Exception as e:
                sg.popup_error(f"保存文件出错: {str(e)}")

        # 统一处理成功提示
        if success and output_path:
            sg.popup("文件已保存", f"保存路径: {output_path}")

window.close()

修改说明

  • 给TabGroup添加了key="-TABGROUP-",通过values["-TABGROUP-"]获取当前选中的标签;
  • 将模板初始化移到了按钮点击事件内,每次生成合同时重新加载原始模板,避免之前的渲染修改污染模板;
  • 统一了成功弹窗逻辑,Vendor分支也会弹出保存提示;
  • 增加了金额输入的异常判断,避免非数字输入导致崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:27:04