在Kivy Canvas中设置值

时间:2018-04-14 20:54:28

标签: python kivy

我遇到了无法解决的问题。问题是:

运行此代码时,

data districtcodes;
 input distnumber distname$;
 str=catt('%censusdata(districtname=', distname, ' , districtnum=', distnumber, 
    ');');
 call execute (str);
 cards;
1   Kaap/Cape   
2   Simonstad   
3   Bellville   
4   Goodwood    
5   Kuilsrivier 
6   Wynberg
;
 ;
 ;; 
run;

我收到此错误:

from kivy.app import App
from kivy.lang import Builder

kv = """

BoxLayout:
    orientation: "vertical"

    my_colors: app.a1,app.a2,app.a3,app.a4
    canvas.before:
        Color:
            rgba: self.my_colors
        Rectangle:
            pos: self.pos
            size: self.size
"""

class d(App):
    def build(self):
        self.a1 = "0.5"
        self.a2 = "0.7"
        self.a3 = "0.222222"
        self.a4 = "0.3456"
        return Builder.load_string(kv)

d().run()

很快,代码就会出现类型错误。你能告诉我我的错吗?

1 个答案:

答案 0 :(得分:0)

问题

由于根小部件, BoxLayout 没有名称为 my_colors 的属性,因此Kivy自动创建了一个 ObjectProperty ,将其添加到小部件中。这导致以下错误,

  

TypeError:' NoneType'对象不可迭代

Kivy Language » Syntax of a kv File

  

如果窗口小部件没有具有给定名称的属性,则为   ObjectProperty将自动创建并添加到窗口小部件中。

解决方案1 ​​

  1. 为根小部件添加一个类。
  2. 在课程级别将 my_colors 声明为 ListProperty
  3. 解决方案2

    使用 设置< key> < expr> 设置全局值。

    #:set my_colors (app.a1, app.a2, app.a3, app.a4)
    

    #:set my_colors [app.a1, app.a2, app.a3, app.a4]
    

    实施例

    解决方案1 ​​ - main.py

    from kivy.app import App
    from kivy.uix.boxlayout import BoxLayout
    from kivy.properties import ListProperty
    from kivy.lang import Builder
    
    kv = """
    RootWidget:
        orientation: "vertical"
    
        my_colors: [app.a1, app.a2, app.a3, app.a4]
    
        canvas.before:
            Color:
                rgba: self.my_colors
            Rectangle:
                pos: self.pos
                size: self.size
    """
    
    
    class RootWidget(BoxLayout):
        my_colors = ListProperty([])
    
    
    class d(App):
    
        def build(self):
            self.a1 = "0.5"
            self.a2 = "0.7"
            self.a3 = "0.222222"
            self.a4 = "0.3456"
            return Builder.load_string(kv)
    
    
    d().run()
    

    解决方案2 - main.py

    from kivy.app import App
    from kivy.lang import Builder
    
    kv = """
    #:set my_colors (app.a1, app.a2, app.a3, app.a4)
    
    BoxLayout:
        orientation: "vertical"
    
        canvas.before:
            Color:
                rgba: my_colors
            Rectangle:
                pos: self.pos
                size: self.size
    """
    
    
    class d(App):
    
        def build(self):
            self.a1 = "0.5"
            self.a2 = "0.7"
            self.a3 = "0.222222"
            self.a4 = "0.3456"
            return Builder.load_string(kv)
    
    
    d().run()
    

    输出

    enter image description here