Python Turtle 等待按键

标签 python turtle-graphics fractals

我想通过让用户在每次移动之前按下一个键来逐步跟随 turtle 绘图。

我可以通过询问用户输入来做到这一点,如下所示:

def wait():
    input('Press a key')

但这是一个糟糕的解决方案,因为焦点离开了 turtle 窗口。

我知道 screen.listen() 并且可以使用 screen.onkeypress() 设置事件监听器。 - 例如 my_screen.onkeypress('wait') 但不确定如何实现。

编辑:我意识到我应该更具体。我正在尝试追踪科赫曲线的递归。到目前为止我的代码如下:

import turtle

def koch(t, order, size):
    """
       Make turtle t draw a Koch fractal of 'order' and 'size'.
       Leave the turtle facing the same direction.
    """
    wait_for_keypress()
    if order == 0:          # The base case is just a straight line
        t.forward(size)
    else:
        koch(t, order-1, size/3)   # Go 1/3 of the way
        t.left(60)
        koch(t, order-1, size/3)
        t.right(120)
        koch(t, order-1, size/3)
        t.left(60)
        koch(t, order-1, size/3)


def wait_for_keypress():
    input('Press a key') # There must be a better way

t = turtle.Turtle()
s = turtle.Screen()
s.listen()

koch(t, 3, 100)

turtle.done()

最佳答案

这听起来像是递归生成器的工作!我们开始运行分形代码,但我们使用 yieldyield from 使其停止沿途的每一步。然后,我们让屏幕点击事件在生成器上执行 next():

from turtle import Turtle, Screen

def koch(t, order, size):
    """
    Make turtle t draw a Koch fractal of 'order' and 'size'.
    Leave the turtle facing the same direction.
    """

    if order == 0:
        t.forward(size)  # The base case is just a straight line
        yield
    else:
        yield from koch(t, order - 1, size / 3)  # Go 1/3 of the way
        t.left(60)
        yield from koch(t, order - 1, size / 3)
        t.right(120)
        yield from koch(t, order - 1, size / 3)
        t.left(60)
        yield from koch(t, order - 1, size / 3)

def click_handler(x, y):
    screen.onclick(None)  # disable handler while in handler

    try:
        next(generator)
    except StopIteration:
        return

    screen.onclick(click_handler)

screen = Screen()

turtle = Turtle()

generator = koch(turtle, 3, 200)

screen.onclick(click_handler)

screen.mainloop()

运行程序。每次在窗口上单击鼠标时,您都会获得科赫分形的附加部分。我们还可以通过关键事件来完成这项工作,保持导入和 koch() 例程相同:

...

def key_handler():
    screen.onkey(None, "Up")  # disable handler while in handler

    try:
        next(generator)
    except StopIteration:
        return

    screen.onkey(key_handler, "Up")

screen = Screen()

turtle = Turtle()

generator = koch(turtle, 3, 200)

screen.onkey(key_handler, "Up")

screen.listen()

screen.mainloop()

请注意,这会响应 turtle 图形窗口中的向上箭头键按下,而不是控制台中的按键按下。

关于Python Turtle 等待按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50446354/

相关文章:

python - 为什么groupby函数会返回重复的数据

python - 尝试使用 Blogger API 删除帖子返回 "not found"错误

python - turtle.done() 在 Spyder 中不起作用

matlab - 用matlab画谢尔宾斯基三角形的高效代码

c++ - Mandelbrot集的多线程计算

python - 以除空格以外的任何内容开头,以扩展名(.png、.jpg、.mp4、.avi、.flv)结尾

python - 以矩阵形式将列表排列到numpy数组

python - 用 turtle 画三角形

Python turtle 模块导致 OS X 崩溃

计算用 XOR 方法编写的谢尔宾斯基三角形的维数