Python kivy。 collide_widget有没有问题?

时间:2018-04-09 16:16:40

标签: python kivy

我正在尝试使用方法collide_widget在kivy中根据小部件的位置打印不同的数字。但是,我不是根据if子句打印1或0,而是同时获得1和0,我不明白为什么。我不知道我哪里错了。如果有人向我解释这将是很好的。

这是我的代码。

from kivy.app import App

from kivy.lang import Builder

from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
from kivy.properties import StringProperty, ObjectProperty

Builder.load_string('''
<Sample@Image>:
    size: self.size
    allow_stretch: False
    keep_ratio: False
    do_rotation: False

<PutOnShelfScreen1>:
    canvas:
        Rectangle:
            source: 'image.png'
            size: self.size
            pos: self.pos
    BoxLayout:
        orientation: 'horizontal'
        spacing: 30
        padding: [10, 150, 10, 10]
        Button:
            id: Tools
            background_color: [63, 191, 63, 0.3]
            text: ''
        Button:
            id: Transportation
            background_color: [63, 191, 63, 0.3]
            text: ''
        Button:
            id: Furniture
            background_color: [63, 191, 63, 0.3]
            text: ''

    StencilView:
        id: elka
        Scatter:
            pos: 500, 500
            size: my_image1.size
            Image:
                id: my_image1
                source: 'block_1\\ель.png'

    StencilView:
        id: armchair
        Scatter:
            pos: 500, 500
            size: my_image2.size
            Image:
                id: my_image2
                source: 'block_1\\armchair.png'
                on_touch_up: root.Count(Furniture, Tools, Transportation, armchair) 
''')

class PutOnShelfScreen1(Screen):
    Tools = Widget()
    Transportation = Widget()
    Furniture = Widget()

    armchair = Widget()

    def Count(self, Furniture, Tools, Transportation, armchair):
        if armchair.collide_widget(Furniture) is True:
            print("1")
        if armchair.collide_widget(Tools) or armchair.collide_widget(Transportation) is True:
            print("0")

sm = ScreenManager()
sm.add_widget(PutOnShelfScreen1(name='class'))

class SampleApp(App):
    def build(self):
        return (sm)

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

1 个答案:

答案 0 :(得分:0)

您已将kv和python代码绑定在一起,但未正确使用该连接。请阅读widget documentation中的ids部分。

在您的代码中,对PutOnShelfScreen1(name='class')的调用会使用您指定的ids创建一个对象。如果您获得对该对象的引用,如:

sm = ScreenManager()
poss1 = PutOnShelfScreen1(name='class')
sm.add_widget(poss1)

然后,您可以使用poss1访问您感兴趣的小部件:

Tools = poss1.ids['Tools']
Transportation = poss1.ids['Transportation']
Furniture = poss1.ids['Furniture']
armchair = poss1.ids['armchair']