如何使用 onkeypress() 进行条件循环?
How do you make a conditional loop with onkeypress()?
我正在为我的介绍 class 开发一个 python 项目,我想用 turtle 模块制作暴风雪。到目前为止,我已经能够在每次按键时都出现一个“雪花”,但我不确定如何将它变成一个条件循环,当我点击时,它会变为 true 并保持循环,而无需我再次点击。
这是我现在拥有的代码:
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)
when I click, it becomes true and keeps looping without me having to
click again.
我们可以制作一个单独的事件处理程序,它是一个 切换 ,使用 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()
当您点击屏幕时,薄片就会开始出现。当您再次单击时,它们将停止。
我正在为我的介绍 class 开发一个 python 项目,我想用 turtle 模块制作暴风雪。到目前为止,我已经能够在每次按键时都出现一个“雪花”,但我不确定如何将它变成一个条件循环,当我点击时,它会变为 true 并保持循环,而无需我再次点击。
这是我现在拥有的代码:
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)
when I click, it becomes true and keeps looping without me having to click again.
我们可以制作一个单独的事件处理程序,它是一个 切换 ,使用 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()
当您点击屏幕时,薄片就会开始出现。当您再次单击时,它们将停止。