2016-03-02 87 views
1

我有一个类,不断改变背景颜色,在init Clock.schedule_interval。我想同时创建这个类的多个实例;但是,我认为这意味着创建不允许的多个线程?我想要的是上半部分改变颜色,而下半部分改变颜色。发生的事情只有下半部分是变化的颜色,而上半部分是黑色的。所以这里是代码。如何在kivy应用程序中同时运行Clock.schedule_interval实例?

的/teacher/main.py文件

from kivy.app import App 
from kivy.clock import Clock 
from kivy.graphics import Color 
from kivy.properties import NumericProperty, ReferenceListProperty 
from kivy.uix.gridlayout import GridLayout 
from kivy.uix.widget import Widget 

from random import randint 

class ChangingBackgroundColor(Widget): 
    r = NumericProperty(.5) 
    g = NumericProperty(.5) 
    b = NumericProperty(.5) 
    a = NumericProperty(1) 
    color = ReferenceListProperty(r, g, b, a) 

    def __init__(self,**kwargs): 
     super(ChangingBackgroundColor, self).__init__(**kwargs) 
     Clock.schedule_interval(self.update, .2) 

    def update(self, dt): 

     position = randint(0,2) # change to randint(0,3) to change a as well 
     direction = randint(0,1) 

     if direction == 0: 
      if self.color[position] == 0: 
       self.color[position] += .1 
      else: 
       self.color[position] -= .1 
     elif direction == 1: 
      if self.color[position] == 1: 
       self.color[position] -= .1 
      else: 
       self.color[position] += .1 

     self.color[position] = round(self.color[position], 2) 
     self.canvas.add(Color(self.color)) 

class TeachingApp(App): 

    def build(self): 
     grid = GridLayout(rows=2) 
     a = ChangingBackgroundColor() 
     b = ChangingBackgroundColor() 
     grid.add_widget(a) 
     grid.add_widget(b) 
     return grid 

if __name__ == '__main__': 
    TeachingApp().run() 

和/teacher/teaching.kv文件

#:kivy 1.0.9 

<ChangingBackgroundColor>: 
    canvas: 
     Color: 
      rgba: self.color 
     Rectangle: 
      size: self.width, self.height 

我看着这里,仍然模糊的线程问题。 Clock documentation

这是我提交的第一个问题,所以如果我对提交问题做了任何错误,请让我知道。

回答

1

你的代码是好的,使用Clock.schedule_interval不使用线程(它全部在主线程中),并且可以从其他线程使用,即使你确实有它们,尽管回调仍然会在主线程中发生。

的问题是,在KV您的矩形记录必须有:

pos: self.pos 

没有这一点,这两个矩形具有默认的POS(0,0),所以第二个是在顶部第一个和屏幕的上半部分是黑色的。

+0

非常感谢你。对于我认为很困难的事情,这种简单的解决方 – pizz

相关问题