0

我在 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()
4

1 回答 1

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()

每次我添加任何东西时,它似乎都会关闭整个程序。

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

于 2013-10-19T14:14:08.337 回答