Kivy手风琴互动

时间:2013-10-19 13:31:39

标签: python input mouse coordinates kivy

我在kivy手风琴中装载了图像,我想在按下鼠标按钮时打印出图像下方的x和y坐标。我不能为了这个人的生活而这样做。每次我添加任何东西,它似乎关闭整个程序。我知道我的小部件将打印到控制台,但我想将其打印到屏幕上。

以下是我正在使用的代码:

from kivy.uix.accordion import Accordion, AccordionItem
from kivy.uix.image import Image
from kivy.app import App
from kivy.uix.widget import Widget

class MouseWidget(Widget):
    def on_touch_down(self, touch):
        print(touch)


class MyApp(App):
    def build(self):
    root = Accordion(orientation='horizontal')

    item= AccordionItem(title='Picture1')
    src = "picture1.png"
    image = Image(source=src,pos=(200, 100))
    # add image to AccordionItem
    item.add_widget(image)
    root.add_widget(item)


    item= AccordionItem(title='Picture2')
    src = "picture2.png" 
    image = Image(source=src,pos=(200, 100))
    # add image to AccordionItem
    item.add_widget(image)
    root.add_widget(item)

    return root

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

1 个答案:

答案 0 :(得分:1)

这是对程序的简单修改,它将触摸位置添加到图像下方的标签上,使用kivy语言自动绑定到必要的属性,以便在显示更改时更新显示。

我不确定你特别遇到了什么问题,所以请告诉我它的工作方式是否不清楚!

from kivy.uix.accordion import Accordion, AccordionItem
from kivy.uix.image import Image
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout

Builder.load_string('''
<MouseWidget>:
    image: image
    label: label
    orientation: 'vertical'
    Image:
        id: image
        source: root.source
    Label:
        id: label
        size_hint_y: None
        height: 50
        text: 'no touch detected'

''')

class MouseWidget(BoxLayout):
    image = ObjectProperty()
    label = ObjectProperty()
    source = StringProperty()

    def on_touch_down(self, touch):
        if self.image.collide_point(*touch.pos):
            self.label.text = str(touch.pos)

    def on_touch_up(self, touch):
        self.label.text = 'no touch detected'


class MyApp(App):
    def build(self):
        root = Accordion(orientation='horizontal')

        item= AccordionItem(title='Picture1')
        src = "picture1.png"
        image = MouseWidget(source=src)
        # add image to AccordionItem
        item.add_widget(image)
        root.add_widget(item)


        item= AccordionItem(title='Picture2')
        src = "picture2.png"
        image = MouseWidget(source=src)
        # add image to AccordionItem
        item.add_widget(image)
        root.add_widget(item)

        return root

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

每次添加任何内容时,似乎都会关闭整个程序。

这听起来像你的更改使程序崩溃了。您应该通过在终端中运行程序来检查程序的输出。它将打印有关错误的信息,以帮助您找出错误。