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

Python程序IDLE运行正常,双击启动闪退无输入,求排查解决

问题解决:Python脚本双击闪退与代码优化

一、窗口闪退的原因与解决

闪退和重复读写文件无关,根源是:直接通过“打开方式>Python”运行脚本时,程序执行完成后会立刻关闭控制台窗口;而IDLE是交互式运行环境,执行结束后会保留窗口供查看输出。

解决方法:

  • 添加等待输入:在程序末尾(比如main()函数最后,或if __name__ == '__main__':块调用main()之后)加上一行代码,让程序等待用户输入后再关闭:
    input("按回车键退出...")
    
  • 用命令行运行:打开命令提示符(CMD),切换到脚本所在文件夹,执行python 你的脚本名.py,执行完窗口会保留,方便查看输出和报错。

二、代码优化:减少重复文件读取

原代码三次打开并读取同一个文件,既浪费IO资源也降低效率。可以改成只读取一次文件,再用读取到的数据生成所有需要的集合和字典:

优化后的完整代码:

def main():
    # 仅读取一次文件,处理所有数据
    with open('worldserieswinners.txt', 'r') as text_file:
        # 读取所有行并去除换行符
        all_teams = [line.rstrip('\n') for line in text_file]
    
    # 生成球队集合
    team_set = set(all_teams)
    print(team_set)
    
    # 统计各球队夺冠次数
    wins_dict = {}
    for team in all_teams:
        wins_dict[team] = wins_dict.get(team, 0) + 1
    
    # 生成年份-冠军字典
    year_dict = {year: '' for year in range(1903, 2010)}
    current_year = 1903
    for team in all_teams:
        year_dict[current_year] = team
        current_year += 1
    
    display_values(year_dict, wins_dict)
    # 添加等待输入,解决双击闪退问题
    input("按回车键退出...")

def display_values(dict_1, dict_2):  
    # 优化年份查询的错误处理逻辑
    while True:
        try:
            search_1 = int(input('Enter a year from 1903 - 2009 to see the World Series Winner: '))
            if 1903 <= search_1 <= 2009:
                winner = dict_1[search_1]
                if winner:
                    print(f'The winner of the {search_1} World Series was {winner}.')
                    break
                else:
                    print(f'There was no World Series in {search_1}.')
                    break
            else:
                print('Invalid year. Please enter a year between 1903 and 2009.')
        except ValueError:
            print('Please enter a valid integer year.')
    
    # 优化球队查询的错误处理逻辑
    while True:
        search_2 = input('Enter team name to see how many times they have won the World Series: ')
        if search_2 in dict_2:
            print(f'The {search_2} have {dict_2[search_2]} wins.')
            break
        else:
            print('That team has never won the World Series, or it was not a valid team name. Please enter another name, making sure to capitalize properly: ')

if __name__ == '__main__':
    main()

优化点说明:

  1. 单次文件读取:使用with语句自动管理文件关闭,一次性读取所有行到列表all_teams,后续所有操作基于该列表完成,避免重复IO操作。
  2. 简化字典生成:
    • 夺冠次数统计直接遍历列表,用dict.get()方法简化计数逻辑,无需预先创建空字典。
    • 年份字典保持原逻辑,但基于已读取的列表填充数据。
  3. 修复错误处理漏洞:原代码的except KeyError存在逻辑问题(比如1904年属于有效年份但无冠军,会再次触发异常),改成循环验证的方式,逻辑更健壮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:20:35