如何访问其他滑块小部件的ID?

时间:2018-10-05 22:43:44

标签: python kivy

<content/>

我正在尝试访问具有Slider: id:slider_id4 min: -90 max: 90 value: 0 step: 1 pos: root.width/2+0.3*root.width/2,0.90*root.height size_hint:0.7,0.05 canvas: PushMatrix Rotate: angle: slider_id4.value origin: 30,65 Color: rgb: [.5,1,.5] Rectangle: pos: 25+slider_id5.value,65 size: 10,25 PopMatrix Slider: id:slider_id5 min: 0 max: 50 value: 0 step: 1 pos: root.width/2+0.3*root.width/2,0.80*root.height size_hint:0.7,0.05 canvas: Color: rgb: [.5,.5,.5] Rectangle: id:r1 pos: 0+slider_id5.value,30 size: 60,20 Color: rgb: [1,.5,.5] Ellipse: pos: 15+slider_id5.value,35 angle_start: 270 angle_end: 450 size: 30,30 的滑块小部件画布中的slider_id5.value,但出现一条错误消息:

  

未定义名字lider_id5

我需要访问id: slider_id4小部件(在Rectangle下)中slider_id5的值。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

当Kivy解析kv文件时, slider_id4 中引用了 slider_id5 时尚未定义。

解决方案

检查app.root中的None

替换

25+slider_id5.value,65

(25, 65) if app.root is None else (app.root.ids.slider_id5.value+25,65)

示例

test.kv

#:kivy 1.11.0

<RootWidget>:
    orientation: 'vertical'


    Slider:
        id: slider_id4

        min: -90
        max: 90
        value: 0
        step: 1
        pos: root.width/2+0.3*root.width/2,0.90*root.height
        size_hint:0.7, 0.05

        canvas:
            PushMatrix
            Rotate:
                angle: slider_id4.value
                origin: 30,65
            Color:
                rgb: [.5,1,.5]
            Rectangle:
                pos: (25, 65) if app.root is None else (app.root.ids.slider_id5.value+25,65)
                size: 10,25
            PopMatrix

    Slider:
        id: slider_id5
        min: 0
        max: 50
        value: 0
        step: 1
        pos: root.width/2+0.3*root.width/2,0.80*root.height
        size_hint:0.7,0.05

        canvas:
            Color:
                rgb: [.5,.5,.5]
            Rectangle:
                id:r1
                pos: 0+slider_id5.value,30
                size: 60,20

            Color:
                rgb: [1,.5,.5]
            Ellipse:
                pos: 15+slider_id5.value,35
                angle_start: 270
                angle_end: 450
                size: 30,30

main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout


class RootWidget(BoxLayout):
    pass


class TestApp(App):

    def build(self):
        return RootWidget()


if __name__ == "__main__":
    TestApp().run()

输出

Img01 - Moved Slider4 Img02 - Moved Slider5