改变乌龟图形的颜色按键按下时。

huangapple go评论91阅读模式
英文:

Changing colors on turtle graphics on key press

问题

我在使用turtle编写代码时遇到了更改颜色的问题,使用colorsys库的hsv_to_rgb函数,除了色相(hue)之外,其他都设置好了。我为色相声明了一个变量,一切都很顺利,直到启动后,它只改变一次。以下是代码:

  1. from turtle import *
  2. from colorsys import *
  3. pencolor('blue')
  4. pensize(2)
  5. bgcolor('black')
  6. default_size = 0
  7. h = 0
  8. def move_up():
  9. sety(ycor() + 50)
  10. def move_left():
  11. setx(xcor() - 50)
  12. def move_right():
  13. setx(xcor() + 50)
  14. def move_down():
  15. sety(ycor() - 50)
  16. def change_color():
  17. n = 0.1
  18. c = hsv_to_rgb((h + n), 1, 1)
  19. color(c)
  20. def call_movement():
  21. onkey(move_up, 'Up')
  22. onkey(move_left, "Left")
  23. onkey(move_right, "Right")
  24. onkey(move_down, "Down")
  25. listen()
  26. def color_change():
  27. onkey(change_color, "+")
  28. listen()
  29. call_movement()
  30. color_change()
  31. 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:

  1. from turtle import *
  2. from colorsys import *
  3. pencolor('blue')
  4. pensize(2)
  5. bgcolor('black')
  6. default_size = 0
  7. h = 0
  8. def move_up():
  9. sety(ycor() + 50)
  10. def move_left():
  11. setx(xcor() - 50)
  12. def move_right():
  13. setx(xcor() + 50)
  14. def move_down():
  15. sety(ycor() - 50)
  16. def change_color():
  17. n = 0.1
  18. c = hsv_to_rgb((h+n), 1, 1)
  19. color(c)
  20. def call_movement():
  21. onkey(move_up, 'Up')
  22. onkey(move_left, "Left")
  23. onkey(move_right, "Right")
  24. onkey(move_down, "Down")
  25. listen()
  26. def color_change():
  27. onkey(change_color, "+")
  28. listen()
  29. call_movement()
  30. color_change()
  31. 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的值,所以它从未改变。

修复:

  1. n = 0.1
  2. ...
  3. def change_color():
  4. global h
  5. h += n
  6. c = hsv_to_rgb(h, 1, 1)
  7. color(c)
英文:

You are not ever setting the value of h, so it never changes.

Fix:

  1. n = 0.1
  2. ...
  3. def change_color():
  4. global h
  5. h += n
  6. c = hsv_to_rgb(h, 1, 1)
  7. color(c)

huangapple
  • 本文由 发表于 2023年2月16日 02:56:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定