Python Turtle等待Keypress

时间:2018-05-21 10:00:51

标签: python turtle-graphics fractals

我希望通过让用户在每次移动前按一个键来逐步跟踪乌龟绘图。

我可以通过询问用户输入来做到这一点:

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

但这是一个可怕的解决方案,因为焦点离开龟窗口。

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

编辑:我意识到我应该更具体一点。我试图跟踪Koch曲线的thr递归。到目前为止我的代码如下:

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

2 个答案:

答案 0 :(得分:1)

这听起来像是一个递归发生器的工作!我们开始运行分形代码,但我们使用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分形的附加部分。我们也可以通过一个关键事件来完成这项工作,保持导入和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()

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

答案 1 :(得分:0)

改变你的功能:

def wait_for_keypress():
    print("'Press a key'")
    fd = sys.stdin.fileno()
    try:
        tty.setraw(fd)
        ch = sys.stdin.read(1)
    except:
        pass

基于Manually control a Python Turtle with the keyboard.

注意:

您必须导入systermiostty