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

如何在PySimpleGUI中实现分数输入时总分自动更新

实现PySimpleGUI分数输入自动更新总分

直接修改你的布局并添加实时计算逻辑,就能实现输入分数时自动更新对应科目总分及总分数:

import PySimpleGUI as sg

layout = [
    [sg.Text("Enter Full Name :"), sg.InputText(key="name")],
    [sg.Text("Gender"), sg.Combo(["Male", "Female"], key="gender")],
    [sg.Text("Enter Enrollment No. :"), sg.InputText(key="enrollno")],
    [sg.Text("Exam Roll No. :"), sg.InputText(key="rollno")],
    [sg.Text("Medium :"), sg.InputText(key="med")],
    # [sg.Text("Compulsory English :"), sg.InputText(key="CE")],
    # [sg.Combo(["Supplementary English","Hindi", "Marathi"]), sg.InputText(key="SL")],
    [sg.Text("Theory 1 :"), sg.InputText(key="T1", enable_events=True), 
     sg.Text("Practical 1 :"), sg.InputText(key="P1", enable_events=True),
     sg.Text("Internal Assessment 1 :"), sg.InputText(key="IA1", enable_events=True),
     sg.Text("Paper 1 Total :"), sg.Text("0", key="paper1_total")],
    [sg.Text("Theory 2 :"), sg.InputText(key="T2", enable_events=True), 
     sg.Text("Practical 2 :"), sg.InputText(key="P2", enable_events=True),
     sg.Text("Internal Assessment 2 :"), sg.InputText(key="IA2", enable_events=True),
     sg.Text("Paper 2 Total :"), sg.Text("0", key="paper2_total")],
    [sg.Text("Grand Total :"), sg.Text("0", key="grand_total")],
    [sg.Button("Submit", key="submit")],
]

window = sg.Window("Score Entry", layout)

def safe_sum(values, key_list):
    total = 0
    for key in key_list:
        try:
            total += int(values[key])
        except (ValueError, TypeError):
            # 非数字输入视为0
            pass
    return total

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    
    # 更新Paper1总分
    if event in ("T1", "P1", "IA1"):
        window["paper1_total"].update(str(safe_sum(values, ["T1", "P1", "IA1"])))
    
    # 更新Paper2总分
    if event in ("T2", "P2", "IA2"):
        window["paper2_total"].update(str(safe_sum(values, ["T2", "P2", "IA2"])))
    
    # 更新总总分
    total_1 = safe_sum(values, ["T1", "P1", "IA1"])
    total_2 = safe_sum(values, ["T2", "P2", "IA2"])
    window["grand_total"].update(str(total_1 + total_2))
    
    if event == "submit":
        # 这里可以添加提交数据的逻辑
        sg.popup("Submitted!")

window.close()

核心改动说明:

  • 给所有分数输入框加上enable_events=True,让输入内容变化时触发事件
  • 添加三个带key的文本控件,分别用来显示Paper1总分、Paper2总分和总分数
  • 写了safe_sum函数处理非数字输入的情况,避免程序报错
  • 在事件循环里监听输入变化,实时计算并更新对应总分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:21:08