PySimpleGUI动态生成输入框求助:窗口切换后崩溃报NoneType
解决PySimpleGUI动态生成输入框的问题
问题根源
你遇到的崩溃是因为关闭旧窗口后,原窗口对象被销毁变为NoneType,后续代码若还尝试引用旧窗口的属性或方法就会报错。频繁关闭重建窗口体验也不佳,更优方案是在当前窗口内动态更新布局,无需重启窗口。
方案1:修复多窗口切换的崩溃问题
如果坚持用多窗口方式,要确保旧窗口彻底关闭后不再引用,且新窗口的事件循环完全独立:
import PySimpleGUI as sg def create_main_window(): layout = [ [sg.Text("请输入要生成的输入框数量:"), sg.Input(key="-NUM-")], [sg.Button("生成输入框"), sg.Button("退出")] ] return sg.Window("主窗口", layout) def create_input_window(num): layout = [[sg.Text(f"输入内容 {i+1}:"), sg.Input(key=f"-INPUT-{i}")] for i in range(num)] layout.append([sg.Button("提交"), sg.Button("返回")]) return sg.Window("输入窗口", layout) # 主窗口事件循环 window = create_main_window() while True: event, values = window.read() if event in (sg.WIN_CLOSED, "退出"): window.close() break if event == "生成输入框": try: num = int(values["-NUM-"]) if num <=0: sg.popup("请输入正整数") continue # 关闭主窗口并打开输入窗口 window.close() input_window = create_input_window(num) while True: input_event, input_values = input_window.read() if input_event in (sg.WIN_CLOSED, "返回"): input_window.close() window = create_main_window() break if input_event == "提交": print("输入内容:", [input_values[f"-INPUT-{i}"] for i in range(num)]) input_window.close() window = create_main_window() break except ValueError: sg.popup("请输入有效的数字")
该方案每次关闭窗口后都会重新创建新窗口对象,避免引用已销毁的None对象。
方案2:动态更新当前窗口(推荐)
直接在当前窗口内添加/移除输入框,无需关闭重建,体验更流畅:
import PySimpleGUI as sg # 初始布局 layout = [ [sg.Text("请输入要生成的输入框数量:"), sg.Input(key="-NUM-"), sg.Button("生成")], # 预留容器放置动态输入框 [sg.Column([], key="-INPUT_CONTAINER-")], [sg.Button("提交"), sg.Button("清空")] ] window = sg.Window("动态输入框生成器", layout) input_keys = [] # 保存动态输入框的key,方便后续获取值 while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event == "生成": try: num = int(values["-NUM-"]) if num <=0: sg.popup("请输入正整数") continue # 清空旧输入框 window["-INPUT_CONTAINER-"].update([]) input_keys.clear() # 生成新输入框布局 new_layout = [] for i in range(num): key = f"-INPUT-{i}" new_layout.append([sg.Text(f"输入内容 {i+1}:"), sg.Input(key=key)]) input_keys.append(key) # 更新容器布局 window.extend_layout(window["-INPUT_CONTAINER-"], new_layout) except ValueError: sg.popup("请输入有效的数字") if event == "提交": if not input_keys: sg.popup("请先生成输入框") continue results = [values[key] for key in input_keys] print("提交的内容:", results) if event == "清空": window["-INPUT_CONTAINER-"].update([]) input_keys.clear() window["-NUM-"].update("") window.close()
核心要点:
- 用
sg.Column作为动态元素的容器,方便统一更新 - 通过
window.extend_layout()向容器添加新布局元素 - 维护列表保存动态输入框的key,便于后续获取输入值
- 每次生成新输入框前清空旧元素,避免重复
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

