整个屏幕不随乌龟移动 [英] Entire screen not moving with the turtle

查看:31
本文介绍了整个屏幕不随乌龟移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 中的 turtle 模块在 python 中制作游戏.我希望屏幕与乌龟一起移动.有什么办法吗?谢谢

I am making a game in python using the turtle module in python. I want the screen to move with the turtle. Is there any way to do it? Thanks

推荐答案

问题是屏幕没有随乌龟一起移动……是吗?有人知道为什么吗?

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

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

I know why. First, @martineau is correct, as usual +1, about passing the wrong range of values to yview_moveto(). But there's another piece to this puzzle: tkinter and turtle do not use the same coordinate system! You need to correct for the coordinate system difference, then turn the value into a percentage.

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

Here's a stripped down example based on your code and desired behavior. It keeps the ball in the middle of the window but you can tell from the numbers, and the vertical scroll bar, it's falling. Tap the the up arrow to slow it down -- tap it again to stop the motion. Tap it once more to start rising. Or use the down arrow to reverse your movement again:

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()

这篇关于整个屏幕不随乌龟移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆