在gui kivy python中按下鼠标添加小部件

2024-07-02 13:27:15 发布

您现在位置:Python中文网/ 问答频道 /正文

每次用鼠标按屏幕时,我都有添加和显示图片的问题。你知道吗

class Myszka(ClickAndGo, Widget):

    def on_touch_down(self, touch):
        super().build()
        flaga_path = os.path.join(self.img_path, "test.png")
        x, y = touch.pos
        self.flaga = Image(source=flaga_path, size_hint=(None, None), size=(64, 64),
                           pos=(round(x, 1), round(y, 1)))
        self.camlayout.add_widget(self.flaga)
        print(touch.pos)
  • 实际结果: 只打印触摸位置,未显示图像。你知道吗
  • 预期结果: 图像应该已经显示,每次鼠标按下。你知道吗

Tags: pathpos图像selfnonesize屏幕图片
2条回答

问题

I have problem with adding and showing image to the layout every time I press the screen using mouse.

根本原因

图像未显示,因为它正在添加到class Myszka()的方法on_touch_down()中的局部属性self.camlayout。你知道吗

解决方案

App.get_running_app().root.add_widget(self.flaga)替换self.camlayout.add_widget(self.flaga),即获取根的实例(camlayout)。你知道吗

代码段-py

class Myszka(Widget):

    def on_touch_down(self, touch):
        ...
        App.get_running_app().root.add_widget(self.flaga)

示例

下面的示例演示如何在鼠标单击FloatLayout的位置添加Image。你知道吗

你知道吗主.py你知道吗

import os
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image


class Mouse(FloatLayout):

    def on_touch_down(self, touch):
        img_path = "/home/iam/Pictures/AppImages"
        flag_path = os.path.join(img_path, "Android_celebrate.png")
        flag = Image(source=flag_path, size_hint=(None, None), size=(64, 64),
                     pos=(round(touch.pos[0], 1), round(touch.pos[1], 1)))
        self.add_widget(flag)


class TestApp(App):

    def build(self):
        return Mouse()


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

输出

Result

@ikolim公司

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout


class ClickAndGo(App):
    def build(self):
        self.camlayout = FloatLayout(size=(100,100))
        self.myszka = Myszka()

        self.camlayout.add_widget(self.myszka)

        return self.camlayout

class Myszka(ClickAndGo, Widget):

    def on_touch_down(self, touch):
        super().build()
        # test.png -> any image
        flaga_path = os.path.join(self.img_path, "test.png")
        x, y = touch.pos
        self.flaga = Image(source=flaga_path, size_hint=(None, None), size=(64, 64),
                           pos=(round(x, 1), round(y, 1)))
        self.camlayout.add_widget(self.flaga)
        print(touch.pos)

相关问题 更多 >