整个屏幕不随乌龟移动

Entire screen not moving with the turtle

我正在 python 使用 python 中的 turtle 模块制作游戏。 我想让屏幕和乌龟一起移动。有什么办法吗?谢谢

The problem is that the screen isn't moving with the turtle ... Does anyone know why?

我知道为什么。首先,@martineau 是正确的,像往常一样 +1,关于将错误的值范围传递给 yview_moveto()。但是这个谜题还有另一块:tkinter 和 turtle 不使用相同的坐标系!您需要修正坐标系差异,然后将值转换为百分比。

这是一个基于您的代码和所需行为的精简示例。它使球保持在 window 的中间,但您可以从数字和垂直滚动条中看出它正在下落。点击向上箭头以减慢速度 - 再次点击以停止运动。再次点击它开始上升。或使用向下箭头再次反转您的移动:

from turtle import Screen, Turtle

WIDTH, DEPTH = 300, 10_000
CURSOR_SIZE = 20

vy = -10

def rise():
    global vy
    vy += 5

def fall():
    global vy
    vy -= 5

def move():
    global vy

    if abs(ball.ycor()) < DEPTH/2:
        ball.forward(vy)

        canvas.yview_moveto((DEPTH/2 - ball.ycor() - WIDTH/2 + CURSOR_SIZE) / DEPTH)

        screen.update()
        screen.ontimer(move)

screen = Screen()
screen.setup(WIDTH, WIDTH)  # visible window
screen.screensize(WIDTH, DEPTH)  # area window peeps into
screen.tracer(False)

canvas = screen.getcanvas()

marker = Turtle()
marker.hideturtle()
marker.penup()
marker.setx(-WIDTH/4)  # so we can see we're moving

for y in range(-DEPTH//2, DEPTH//2, 100):
    marker.sety(y)
    marker.write(y, align='right')

ball = Turtle('circle')
ball.speed('fastest')
ball.setheading(90)
ball.penup()

screen.onkey(rise, 'Up')
screen.onkey(fall, 'Down')
screen.listen()

move()

screen.mainloop()