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

Mac上Python Turtle图形界面缓冲报错,在线编译器正常运行求助

Mac本地运行Python Turtle海龟赛跑代码的报错解决方案

问题说明

这段海龟赛跑代码在在线Replit编译器中可正常运行,但在Mac本地运行时,会出现Turtle图形界面缓冲卡顿,同时抛出_tkinter.TclError错误,提示**"can't invoke 'bind' command: application has been destroyed"**,调整代码缩进后问题仍存在。

原代码

import random
import turtle
colors = ["red", "yellow", "blue", "green", "orange","purple"]
Turtles = []
for i in range(0, 6):
    my_turtle = turtle.Turtle(shape="turtle")
    my_turtle.penup()
    my_turtle.color(colors[i])
    Turtles.append(my_turtle)

screen = turtle.Screen()
screen.setup(height=500, width=400)
user_input = screen.textinput(title="Make your bet",prompt="Which turtle is going to win the race?..")
print(user_input)
x = -230
y = 150
for i in range(len(colors)):
    Turtles[i].goto(x=x, y=y)
    y -= 50

game_start = False

if user_input:
    game_start = True

while game_start:
    for i in range(0, 6):
        random_num = random.randint(0, 10)
        Turtles[i].forward(random_num)
        if Turtles[i].xcor() >= 230.00:
            game_start = False
            if Turtles[i].color()[0] == user_input:
                print(f"The Turtle with color {user_input} Won..You Won")
            else:
                print(f'The Turtle with color {Turtles[i].color()[0]} Won..You lose')

            i = 6

screen.exitonclick()

报错信息

Traceback (most recent call last):
  File "/Users/hassanmuzaffar/Documents/VS CODE/Python/Day19.py", line 48, in <module>
    my_turtle = turtle.Turtle(shape="turtle")
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/turtle.py", line 3813, in __init__
    Turtle._screen = Screen()
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/turtle.py", line 3663, in Screen
    Turtle._screen = _Screen()
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/turtle.py", line 3691, in __init__
    TurtleScreen.__init__(self, _Screen._canvas)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/turtle.py", line 996, in __init__
    self.clear()
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/turtle.py", line 1028, in clear
    self.onclick(None, btn)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/turtle.py", line 1365, in onclick
    self._onscreenclick(fun, btn, add)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/turtle.py", line 669, in _onscreenclick
    self.cv.unbind("<Button-%s>" % num)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/turtle.py", line 422, in unbind
    self._canvas.unbind(*args, **kwargs)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 1397, in unbind
    self.tk.call('bind', self._w, sequence, '')
_tkinter.TclError: can't invoke "bind" command:  application has been destroyed

错误解释:该错误是因为tkinter应用实例已被销毁,但代码仍尝试调用其绑定事件(bind)方法,根源是Turtle和Screen实例的创建顺序不当,加上while循环阻塞了tkinter的事件循环。

解决方法及修改后代码

核心修改点

  1. 调整创建顺序:先创建Screen实例,再创建海龟对象。因为Turtle默认会自动生成Screen,手动后续创建会导致多实例冲突,Mac环境下tkinter对此兼容性更差。
  2. 替换while循环:用turtle.ontimer()代替while循环,避免阻塞tkinter的事件循环,解决界面缓冲卡顿问题。
  3. 优化终止逻辑:移除无效的i=6终止循环,改用标志位控制游戏结束。

修改后的代码

import random
import turtle

colors = ["red", "yellow", "blue", "green", "orange", "purple"]
Turtles = []

# 先创建屏幕实例,再创建海龟
screen = turtle.Screen()
screen.setup(height=500, width=400)
user_input = screen.textinput(title="Make your bet", prompt="Which turtle is going to win the race?..")
print(user_input)

# 创建并初始化海龟
x = -230
y = 150
for color in colors:
    my_turtle = turtle.Turtle(shape="turtle")
    my_turtle.penup()
    my_turtle.color(color)
    my_turtle.goto(x=x, y=y)
    Turtles.append(my_turtle)
    y -= 50

game_start = bool(user_input)

def race_step():
    global game_start
    if not game_start:
        return
    
    for turtle in Turtles:
        if turtle.xcor() >= 230.00:
            game_start = False
            winner_color = turtle.color()[0]
            if winner_color == user_input:
                print(f"颜色为{user_input}的海龟获胜!你赢了")
            else:
                print(f"颜色为{winner_color}的海龟获胜!你输了")
            return
        
        random_num = random.randint(0, 10)
        turtle.forward(random_num)
    
    # 递归调用,每50ms执行一次比赛步骤,保证界面响应
    screen.ontimer(race_step, 50)

if game_start:
    race_step()

screen.exitonclick()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:00:55