python - 如何在Python中单独更新 turtle

标签 python python-3.x turtle-graphics

我目前正在尝试在 python 中单独更新多个 turtle 。在下面显示的示例中,我尝试让底部 turtle 移动并根据玩家输入不断更新,而顶部 turtle 向前和向后移动并根据一定的间隔进行更新。

import turtle
from time import sleep
from turtle import Screen, Turtle

screen = turtle.Screen()
screen.title("Turtle Test")
screen.bgcolor("grey")
screen.setup(width=630, height=630)
screen.tracer(0)

turtle_a = turtle.Turtle()
turtle_a.speed(0)
turtle_a.shape("square")
turtle_a.color("white")
turtle_a.penup()

turtle_b = turtle.Turtle()
turtle_b.speed(0)
turtle_b.shape("square")
turtle_b.color("black")
turtle_b.penup()

turtle_b_speed = 10

def go_left():
    x = turtle_b.xcor()
    x -= turtle_b_speed
    turtle_b.setx(x)

def go_right():
    x = turtle_b.xcor()
    x += turtle_b_speed
    turtle_b.setx(x)

screen.listen()
screen.onkeypress(go_left, "Left")
screen.onkeypress(go_right, "Right")

direct = 5

while True:
    turtle_a.goto(turtle_a.xcor() + direct, turtle_a.ycor())
    sleep(0.5)
    if turtle_a.xcor() >= 310:
        direct = -5
    if turtle_a.xcor() <= -310:
        direct = 5
    # update function

最佳答案

当您以两种不同的方式导入turtle两次以及在像turtle这样的基于事件的环境中使用sleep()时,您就知道您已经走上了错误的道路:

import turtle
from time import sleep
from turtle import Screen, Turtle

您也不应该在基于事件的环境中使用 while True: 循环,而应该使用计时器事件。下面是修复这些问题的代码的重写。由于您从未为两只 turtle 设置 Y 坐标,因此没有“顶部”或“底部”,只有两只 turtle 彼此移动:

from turtle import Screen, Turtle

def go_left():
    x = turtle_b.xcor() - turtle_b_speed

    if -300 <= x <= 300:
        turtle_b.setx(x)

def go_right():
    x = turtle_b.xcor() + turtle_b_speed

    if -300 <= x <= 300:
        turtle_b.setx(x)

def move_a():
    global turtle_a_direct

    turtle_a.setx(turtle_a.xcor() + turtle_a_direct)

    if not -300 <= turtle_a.xcor() <= 300:
        turtle_a.undo()
        turtle_a_direct *= -1

    screen.ontimer(move_a, 500)

screen = Screen()
screen.title("Turtle Test")
screen.bgcolor('grey')
screen.setup(width=640, height=640)

turtle_a = Turtle('square')
turtle_a.speed('fastest')
turtle_a.color('white')
turtle_a.penup()

turtle_a_direct = 5

turtle_b = Turtle('square')
turtle_b.speed(0)
turtle_b.color('black')
turtle_b.penup()

turtle_b_speed = 10

screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')
screen.listen()

move_a()

screen.mainloop()

由于您调用了 onkeypress(),我假设使用的是 Python 3。

关于python - 如何在Python中单独更新 turtle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952490/

相关文章:

python - 这行代码使程序对重启功能无 react

python - 测试生成器大小然后显示它的 Pythonic 方法是什么?

Python lxml 自定义解析器不适用于 lxml.etree.parse(...) 函数

python-3.x - 没有名为 'turtle' 的模块

python - 如何使用 Python Dropbox API v2 读取 Dropbox 文件夹内的文件?

python - 在python中识别具有不同列名的重复列值的列

Python 3.0 使用turtle.onclick

python - 如何停止和重启 Telegram Bot

python - Pika blocking_connection.py 随机超时连接到 RabbitMQ

python - Pandas corr() 返回 NaN 的频率太高