<h2>问题</h2>
<blockquote>
<p>I have problem with adding and showing image to the layout every time
I press the screen using mouse.</p>
</blockquote>
<h2>根本原因</h2>
<p>图像未显示,因为它正在添加到<code>class Myszka()</code>的方法<code>on_touch_down()</code>中的局部属性<code>self.camlayout</code>。你知道吗</p>
<h2>解决方案</h2>
<p>用<code>App.get_running_app().root.add_widget(self.flaga)</code>替换<code>self.camlayout.add_widget(self.flaga)</code>,即获取根的实例(<code>camlayout</code>)。你知道吗</p>
<h2>代码段-py</h2>
<pre><code>class Myszka(Widget):
def on_touch_down(self, touch):
...
App.get_running_app().root.add_widget(self.flaga)
</code></pre>
<h2>示例</h2>
<p>下面的示例演示如何在鼠标单击<code>FloatLayout</code>的位置添加<code>Image</code>。你知道吗</p>
<h2>你知道吗主.py你知道吗</h2>
<pre><code>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()
</code></pre>
<h2>输出</h2>
<p><a href="https://i.stack.imgur.com/GDJOR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GDJOR.png" alt="Result"/></a></p>