输入 screen.tracer(0) 时,Turtle 图形窗口没有响应

问题描述 投票:0回答:1
from turtle import Screen, Turtle

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

starting_positions = [(0, 0), (-20, 0), (-40, 0)]

segments = []

for position in starting_positions:
    new_segment = Turtle("square")
    new_segment.penup()
    new_segment.color("white")
    new_segment.goto(position)
    segments.append(new_segment)

game_is_on = True
while game_is_on:
    for seg in segments:
        seg.forward(20)

screen.exitonclick()

当我执行上面的代码时,它给出:output

请问有人可以告诉我为什么会发生这种情况以及解决此问题的方法吗?

pycharm turtle-graphics python-turtle
1个回答
0
投票

你有一个无限循环:

game_is_on = True
while game_is_on:
    # do stuff that never changes game_is_on to False or breaks the loop

screen.tracer(0)
禁用通常管理对海龟函数调用的内部渲染循环(如
seg.forward(20)
),将代码的控制权交给海龟客户端代码(这意味着你!)。您需要实现某种方法来定期将线程中的控制推迟到海龟线程,以便它有机会刷新 GUI 并处理交互。

但是当您触发无限循环时,就会无限期地锁定代码并且 GUI 变得无响应。

处理此问题的典型方法是

turtle.update
turtle.ontimer
update
要求turtle渲染一帧,
ontimer
t
毫秒后执行回调。

这是让事情再次运转的一种方法:

import turtle
from turtle import Screen, Turtle

frame_delay_ms = 80
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

starting_positions = [(0, 0), (-20, 0), (-40, 0)]

segments = []

for position in starting_positions:
    new_segment = Turtle("square")
    new_segment.penup()
    new_segment.color("white")
    new_segment.goto(position)
    segments.append(new_segment)

def tick():
    for seg in segments:
        seg.forward(20)

    turtle.update()
    screen.ontimer(tick, frame_delay_ms)

tick()
screen.exitonclick()
© www.soinside.com 2019 - 2024. All rights reserved.