[英]Add widget on mouse pressed in gui - kivy python
I have problem with adding and showing image to the layout every time I press the screen using mouse. 每次使用鼠标按屏幕时,我都会在布局中添加和显示图像时出现问题。
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)
@ikolim @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)
I have problem with adding and showing image to the layout every time I press the screen using mouse. 每次使用鼠标按屏幕时,我都会在布局中添加和显示图像时出现问题。
The image is not showing because it is adding to a local attribute, self.camlayout
in method on_touch_down()
of class Myszka()
. 图像未显示,因为它正在class Myszka()
方法on_touch_down()
中添加到本地属性self.camlayout
。
Replace self.camlayout.add_widget(self.flaga)
with App.get_running_app().root.add_widget(self.flaga)
ie get an instance of the root ( camlayout
). 将self.camlayout.add_widget(self.flaga)
替换为App.get_running_app().root.add_widget(self.flaga)
即获取根的实例( camlayout
)。
class Myszka(Widget):
def on_touch_down(self, touch):
...
App.get_running_app().root.add_widget(self.flaga)
The following example illustrates adding Image
at the position of the mouse click on a FloatLayout
. 以下示例说明了在FloatLayout
上单击鼠标时添加Image
。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.