Guizero程序问题求助:空白窗口与重复错误弹窗修复
解决Guizero车辆信息查询程序的两个问题
问题描述
- 点击“Last 3 Drivers”按钮仅弹出空白窗口,无法展示关联驾驶员数据
- 未选中车辆时点击任意按钮,错误弹窗会重复弹出多次
问题原因分析
问题1(空白窗口)
- 组件绑定错误:
Last_Driv函数中创建的窗口是newwindow,但添加文本组件时误写为window(该变量仅在Get_Info中定义,此处未生效) - 文件遍历逻辑错误:外层已遍历一次CSV文件,内层再次遍历会导致文件指针移至末尾,无法读取有效数据
- 关联条件错误:原代码用
items2[1]与选中车辆匹配,假设第二个CSV的第一列(items2[0])才是关联的车辆名称,匹配逻辑错误 - 未处理换行符:CSV行拆分后的数据可能包含换行符,导致内容显示异常
问题2(重复错误弹窗)
两个按钮的处理函数中,选中判断逻辑放在了文件遍历循环内部,导致CSV文件每一行都会触发一次错误弹窗,最终重复弹出多次
修复后的完整代码
from guizero import App, ListBox, Text, PushButton, Window app = App("Cars", layout='grid') app.height = 350 app.width = 350 app.bg = 'gray' text = Text(app, grid=[0,0], text="Buy a Car here!!!!!!\n(Cars are guaranteed to breakdown,no refunds)") text2 = Text(app, grid=[0,70], text="Select the Car to learn more\n information about it") text2.size = '10' listbox = ListBox(app, grid=[0,50]) listbox.bg = 'white' listbox.text_size = "10" # 读取车辆数据填充ListBox,处理换行符 with open('Cars database.csv') as fh: for line in fh: line = line.strip() # 移除换行符 items = line.split(",") if len(items) >=2: # 避免空行或格式错误的行 listbox.append(items[1]) def Get_Info(): # 先判断是否选中车辆,放在循环外 if not listbox.value: app.error('Error', text='You must select a car first') return window = Window(app) window.height = 250 window.width = 250 with open('Cars database.csv') as fh: for line in fh: line = line.strip() items = line.split(",") if len(items) >=8 and items[1] == listbox.value: output = ( f"Car: {items[1]}\n" f"Model: {items[2]}\n" f"Color: {items[3]}\n" f"Body-Style: {items[4]}\n" f"Age: {items[5]}\n" f"Year: {items[6]}\n" f"Engine: {items[7]}" ) txt = Text(window, text=output) txt.size = '13' break # 找到匹配项后停止遍历 def Last_Driv(): # 先判断是否选中车辆,放在循环外 if not listbox.value: app.error('Error', text='You must select a car first') return newwindow = Window(app) newwindow.height = 250 newwindow.width = 250 with open('Cars Drivers.csv') as fh: for line in fh: line = line.strip() items2 = line.split(",") # 假设CSV第一列是车辆名称,与ListBox选中值匹配 if len(items2) >=7 and items2[0] == listbox.value: output2 = ( f"Name: {items2[1]}\n" f"Crashes: {items2[2]}\n" f"Name2: {items2[3]}\n" f"Crashes2: {items2[4]}\n" f"Name3: {items2[5]}\n" f"Crashes3: {items2[6]}" ) txt2 = Text(newwindow, text=output2) txt2.size = '13' break # 找到匹配项后停止遍历 my_button = PushButton(app, text='Get Info', grid=[0,80], command=Get_Info) my_button2 = PushButton(app, text='Last 3 Drivers', grid=[0,90], command=Last_Driv) app.display()
关键修改说明
- 错误弹窗重复问题:将
listbox.value的判断移至文件遍历循环外,且判断后直接return,确保仅弹出一次错误提示 - 空白窗口问题:
- 修正窗口变量名,将
Text(window, ...)改为Text(newwindow, ...) - 移除嵌套的文件遍历循环,改为单次遍历
- 调整关联匹配条件为
items2[0] == listbox.value(根据实际CSV结构可自行调整列索引) - 增加
strip()处理换行符,用f-string优化输出格式 - 添加长度判断
len(items) >=X,避免格式错误的CSV行导致索引越界 - 找到匹配数据后用
break停止遍历,提升效率
- 修正窗口变量名,将
内容的提问来源于stack exchange,提问作者Nasrullah Hussain
相关产品推荐
相关产品推荐

