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

PyCharm中screen.listen()执行失败,海龟穿越游戏无法正常运行

问题分析与修复方案

核心问题点

  • 按键绑定错误:screen.onkey(player.go_up(), "Up")里的player.go_up()会直接执行函数,而非把函数绑定到按键上。正确做法是传递函数引用,去掉括号。
  • 死循环阻塞事件处理:while game_is_on是无限循环,会霸占主线程,导致turtle的事件循环(处理按键、窗口关闭等)无法运行,所以screen.listen()和screen.exitonclick()完全失效。不能用time.sleep()配合while循环,得用turtle自带的ontimer方法实现动画更新,让事件循环正常工作。
  • 多余的TurtleScreen._RUNNING设置:这个语句会干扰turtle的正常事件逻辑,完全没必要保留。

修正后的代码

import turtle
from turtle import Screen
from player import Player

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)

player = Player()

screen.listen()
# 修复:传递函数引用,不再直接调用函数
screen.onkey(player.go_up, "Up")

game_is_on = True

def game_loop():
    if game_is_on:
        screen.update()
        # 每100毫秒触发一次循环,实现动画刷新
        screen.ontimer(game_loop, 100)

# 启动游戏循环
game_loop()

# 现在能正常响应窗口点击关闭
screen.exitonclick()

说明

  • 用ontimer替代while循环后,程序在更新动画的同时,能正常处理按键、窗口关闭等事件;
  • 按键绑定改为传递函数引用后,按下上方向键时才会触发player.go_up();
  • 移除多余的TurtleScreen._RUNNING设置,让turtle按默认逻辑运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:07:49