英文:
Changing colors on turtle graphics on key press
问题
我在使用turtle编写代码时遇到了更改颜色的问题,使用colorsys库的hsv_to_rgb函数,除了色相(hue)之外,其他都设置好了。我为色相声明了一个变量,一切都很顺利,直到启动后,它只改变一次。以下是代码:
from turtle import *
from colorsys import *
pencolor('blue')
pensize(2)
bgcolor('black')
default_size = 0
h = 0
def move_up():
sety(ycor() + 50)
def move_left():
setx(xcor() - 50)
def move_right():
setx(xcor() + 50)
def move_down():
sety(ycor() - 50)
def change_color():
n = 0.1
c = hsv_to_rgb((h + n), 1, 1)
color(c)
def call_movement():
onkey(move_up, 'Up')
onkey(move_left, "Left")
onkey(move_right, "Right")
onkey(move_down, "Down")
listen()
def color_change():
onkey(change_color, "+")
listen()
call_movement()
color_change()
done()
我尝试使用while循环并将h的限制设置为1,它可以工作,但不符合我的预期,它循环进行,但我希望它只改变一次,然后将更改存储在变量中,以便在下次按键时使用,创建一种部分循环的效果。
英文:
I was writing a code on turtle and I got stuck in changing colors "onkey", using colorsys (hsv_to_rgb) with everything set but hue, I declared a variable for it. It was going all well till launch, it only changes once. Here's the code:
from turtle import *
from colorsys import *
pencolor('blue')
pensize(2)
bgcolor('black')
default_size = 0
h = 0
def move_up():
sety(ycor() + 50)
def move_left():
setx(xcor() - 50)
def move_right():
setx(xcor() + 50)
def move_down():
sety(ycor() - 50)
def change_color():
n = 0.1
c = hsv_to_rgb((h+n), 1, 1)
color(c)
def call_movement():
onkey(move_up, 'Up')
onkey(move_left, "Left")
onkey(move_right, "Right")
onkey(move_down, "Down")
listen()
def color_change():
onkey(change_color, "+")
listen()
call_movement()
color_change()
done()
I tried using while and set limit to h = 1, it works but not how I want it, it cycles but I want it to go once store the changes on the variable for the next time I use the key, creating a sort of a partial cycle or so
答案1
得分: 1
你没有设置h
的值,所以它从未改变。
修复:
n = 0.1
...
def change_color():
global h
h += n
c = hsv_to_rgb(h, 1, 1)
color(c)
英文:
You are not ever setting the value of h
, so it never changes.
Fix:
n = 0.1
...
def change_color():
global h
h += n
c = hsv_to_rgb(h, 1, 1)
color(c)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论