英文:
How do I change the color of ellipse to a randint every two seconds in Kivy, using random integers
问题
class CanvasExample5(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.ball_size = dp(50)
with self.canvas:
self.color = Color(0, 1, 0)
self.ball = Ellipse(pos=self.center, size=(self.ball_size, self.ball_size))
Clock.schedule_interval(self.update, 1/60)
Clock.schedule_interval(self.colour, 1)
self.vx = dp(5)
self.vy = dp(3)
def on_size(self, *args):
self.ball.pos = (self.center_x-self.ball_size/2, self.center_y-self.ball_size/2)
def colour(self, *args):
random_1 = random.randint(0, 255)
random_2 = random.randint(0, 255)
random_3 = random.randint(0, 255)
self.color = Color(random_1, random_2, random_3)
英文:
class CanvasExample5(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.ball_size = dp(50)
with self.canvas:
self.color = Color(0, 1, 0)
self.ball = Ellipse(pos=self.center, size=(self.ball_size, self.ball_size))
Clock.schedule_interval(self.update, 1/60)
Clock.schedule_interval(self.colour, 1)
self.vx = dp(5)
self.vy = dp(3)
def on_size(self, *args):
self.ball.pos = (self.center_x-self.ball_size/2, self.center_y-self.ball_size/2)
def colour(self, *args):
random_1 = random.randint(0, 255)
random_2 = random.randint(0, 255)
random_3 = random.randint(0, 255)
self.color = Color(random_1, random_2, random_3)
答案1
得分: 1
Ellipse
图形命令使用执行时生效的 Color
,因此之后更改 Color
不会影响 Ellipse
。一个修复方法是清除画布,然后使用新的 Color
重新绘制 Ellipse
:
def colour(self, *args):
random_1 = random.random()
random_2 = random.random()
random_3 = random.random()
self.canvas.clear()
with self.canvas:
Color(random_1, random_2, random_3)
self.ball = Ellipse(pos=self.center, size=(self.ball_size, self.ball_size))
此外,请注意,Color
命令接受的值范围在 0 到 1 之间,而不是 0 到 255。
英文:
The Ellipse
graphics command uses the Color
that is in effect at the time it is executed, so changing the Color
afterwards will have no effect on the Ellipse
. One fix is to clear the canvas and redraw the Ellipse
with the new Color
:
def colour(self, *args):
random_1 = random.random()
random_2 = random.random()
random_3 = random.random()
self.canvas.clear()
with self.canvas:
Color(random_1, random_2, random_3)
self.ball = Ellipse(pos=self.center, size=(self.ball_size, self.ball_size))
Also, note that the Color
command takes values between 0 and 1, not 0 to 255.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论