基于PySimpleGUI为条件while循环添加进度条的求助
问题分析与修复方案
你的进度条未生效主要有几个核心问题:
- 进度条更新逻辑和实际数据处理完全脱节,只是在事件循环末尾执行了无关的固定循环
- 使用
apply批量处理地址时,无法实时跟踪单条数据的处理进度 - 存在语法错误:
i=i+=1是无效写法 - 数据处理过程中窗口会卡顿,没有给GUI留刷新的机会
修改后的完整代码
import PySimpleGUI as sg import pandas as pd from geopy.geocoders import Nominatim from geopy.extra.rate_limiter import RateLimiter sg.theme("DarkTeal2") layout = [ [sg.T("")], [sg.Text("Import file: "), sg.Input(), sg.FileBrowse(key="-IN-")], [sg.Button("Submit"), sg.Button("Exit")], [sg.ProgressBar(1, orientation='h', size=(50, 10), key='progressbar')] ] window = sg.Window('Geocoder', layout, size=(600,150)) progress_bar = window['progressbar'] while True: event, values = window.read() if event == sg.WIN_CLOSED or event=="Exit": break if event == "Submit": file_path = values["-IN-"] if not file_path: sg.popup("请先选择文件") continue # 初始化地理编码工具 geolocator = Nominatim(user_agent="geoapiExercises") geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1) # 读取数据 df = pd.read_csv(file_path, encoding='unicode_escape') total_rows = len(df) # 把进度条最大值设为数据总行数 progress_bar.update(max=total_rows) # 逐行处理地址,实时更新进度 df['location'] = None df['Lat'] = None df['Lon'] = None for idx, row in df.iterrows(): location = geocode(row['add']) df.at[idx, 'location'] = location df.at[idx, 'Lat'] = location.latitude if location else None df.at[idx, 'Lon'] = location.longitude if location else None # 更新当前进度 progress_bar.update(current_count=idx+1) # 强制刷新窗口,避免卡顿 window.refresh() # 保存结果 df.to_csv('Geo_test.csv', index=False) sg.popup("处理完成,结果已保存为Geo_test.csv") window.close()
关键改动说明
- 进度与数据绑定:根据数据总行数设置进度条最大值,每处理一行就同步更新进度
- 逐行替代批量处理:用
iterrows替换apply,实现单条数据的进度跟踪 - 窗口刷新:每次更新进度后调用
window.refresh(),确保GUI保持响应不卡顿 - 路径修复:直接使用选中的完整文件路径,避免文件不在当前目录时出错
- 体验优化:增加未选文件的提示,处理完成后弹出通知
- 语法修正:移除无效的
i=i+=1写法
内容的提问来源于stack exchange,提问作者Ren_07
相关产品推荐
相关产品推荐

