Python运行时如何终止Pygame程序中的无限循环
解决Pygame无限循环导致窗口无法关闭的问题
紧急终止卡死进程的方法
不用重启电脑,直接杀掉Python进程即可:
- Windows:按下
Ctrl+Shift+Esc打开任务管理器,找到python.exe或pythonw.exe进程,右键选择「结束任务」;也可以在命令行执行:taskkill /f /im python.exe - Mac/Linux:打开活动监视器(Mac),或者在终端执行
pkill python/killall python直接终止所有Python进程;若知道进程ID,也可使用kill <PID> - 终端运行时,尝试
Ctrl+Z挂起进程,再输入kill %1(bash环境)杀掉当前挂起的进程
你的代码问题分析
核心问题是无限循环未设置有效终止条件:
你定义了loop = 1,在捕获QUIT事件时将loop = 0,但循环用的是while True:,完全没有判断loop的值,导致点击关闭按钮后循环不会停止,pygame.quit()永远无法执行。
另外代码还存在重复导入pygame、重复调用pygame.display.set_mode()的冗余问题,也会造成不必要的资源浪费。
修正后的代码示例
将循环改为基于loop变量判断,或直接在QUIT事件中退出程序:
import pygame import sys # 导入sys模块用于直接退出程序 # 初始化变量 width = 1366 height = 704 screen = pygame.display.set_mode((width, height)) # 方块类型列表 items = [ # 建筑方块 ["grass", "dirt", "stone", "ore", "chest", "item collector", "block placer", "item dropper"], # 技术方块 ["wires", "sensor", "AND gate", "OR gate", "NOT gate", "NOR gate", "XOR gate", "XNOR gate", "NAND gate", "gearbox", "gear - 24 tooth", "gear - 8 tooth", "item pipe", "filter pipe", "delete pipe", "motor", "joint", "bearing", "blueprints", "spring"], ] # 初始化pygame pygame.init() def init_screen_and_clock(): global screen, clock pygame.display.set_caption('Game') clock = pygame.time.Clock() def create_fonts(font_sizes_list): "批量创建不同字号的字体" fonts = [] for size in font_sizes_list: fonts.append(pygame.font.SysFont("Arial", size)) return fonts def render(fnt, what, color, where): "渲染文本并绘制到屏幕" text_to_show = fnt.render(what, 0, pygame.Color(color)) screen.blit(text_to_show, where) def display_fps(): "显示帧率" render( fonts[0], what=str(int(clock.get_fps())), color="white", where=(0, 0)) init_screen_and_clock() # 创建不同字号的字体 fonts = create_fonts([32, 16, 14, 8]) loop = 1 while loop: # 基于loop变量判断循环是否继续 screen.fill((0, 0, 0)) display_fps() for event in pygame.event.get(): if event.type == pygame.QUIT: loop = 0 # 也可以直接用sys.exit()快速退出 # sys.exit() clock.tick(60) pygame.display.flip() pygame.quit() print("Game over")
内容的提问来源于stack exchange,提问作者Mecode2
相关产品推荐
相关产品推荐

