【问题标题】:How do you make a conditional loop with onkeypress()?如何使用 onkeypress() 进行条件循环?
【发布时间】:2022-01-20 02:47:24
【问题描述】:

我正在为我的介绍类开发一个 python 项目,我想用海龟模块制作暴风雪。到目前为止,我已经能够在每个按键上出现一个“雪花”,但我不知道如何使它成为一个条件循环,当我点击它时,它会变成真的并继续循环,而无需我再次点击。

这是我现在拥有的代码:

def snowing(x, y):
        w.speed(0)
        flake_size = randint(1, 5)
        rx = randint(-250, 250)
        ry = randint(-300, 300)
        w.color(colours[5])
        w.setposition(rx, ry)
        w.pendown()
        w.begin_fill()
        w.circle(flake_size)
        w.end_fill()
        w.penup()
listen()
onscreenclick(snowing, add=None)

【问题讨论】:

    标签: python turtle-graphics python-turtle


    【解决方案1】:

    当我点击时,它变成了真实的并不断循环,而我不必 再次点击。

    我们可以创建一个单独的事件处理程序,即 toggle,使用global 在后续点击时在打开和关闭之间切换。我们将把它与一个计时器事件结合起来,以保持薄片的到来:

    from turtle import Screen, Turtle
    from random import randint, choice
    
    COLOURS = ['light gray', 'white', 'pink', 'light blue']
    
    is_snowing = False
    
    def toggle_snowing(x, y):
        global is_snowing
    
        if is_snowing := not is_snowing:
            screen.ontimer(drop_flake)
    
    def drop_flake():
        flake_radius = randint(1, 5)
    
        x = randint(-250, 250)
        y = randint(-300, 300)
    
        turtle.setposition(x, y)
        turtle.color(choice(COLOURS))
    
        turtle.begin_fill()
        turtle.circle(flake_radius)
        turtle.end_fill()
    
        if is_snowing:
            screen.ontimer(drop_flake)
    
    turtle = Turtle()
    turtle.hideturtle()
    turtle.speed('fastest')
    turtle.penup()
    
    screen = Screen()
    screen.setup(500, 600)
    screen.bgcolor('dark blue')
    screen.onclick(toggle_snowing)
    screen.listen()
    
    screen.mainloop()
    

    当您点击屏幕时,薄片将开始出现。当您再次单击时,它们将停止。

    【讨论】:

    • 非常感谢,这非常有帮助! :D
    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2012-12-06
    相关资源
    最近更新 更多