gpt4 book ai didi

python - Kivy 获取被按下的对象

转载 作者:行者123 更新时间:2023-12-05 03:52:53 28 4
gpt4 key购买 nike

我有一个 Kivy 应用程序,其中有一个 ScrollView 。在这个 ScrollView 中,有一个包含大量图像的框布局,它会在整个运行时发生变化(它可以随时从 1 变为 300)。当触地事件发生时,我需要知道用户按下了哪个图像(意思是他们当时“打开”了哪个图像,因为它们可以上下滚动),甚至可能获得按下相对于图像而不是整个屏幕(我需要在他们按下的地方画画,我不能在不知道他们按下的图像和位置的情况下进行绘制)。我该怎么做?

kv文件中是这样定义的:


MyScrollView:
bar_color: [1, 0, 0, 1]
id: notebook_scroll
padding: 0
spacing: 0
do_scroll: (False, True) # up and down
BoxLayout:
padding: 0
spacing: 0
orientation: 'vertical'
id: notebook_image
size_hint: 1, None
height: self.minimum_height
MyImage:

<MyImage>:
source: 'images/notebook1.png'
allow_stretch: True
keep_ratio: False
size: root.get_size_for_notebook()
size_hint: None, None

它基本上是一个无限笔记本,在运行时,python 代码向 boxlayout(这是笔记本页面的照片)添加了更多“MyImage”对象。

最佳答案

尝试将此方法添加到您的 MyImage:

def to_image(self, x, y):
''''
Convert touch coordinates to pixels

:Parameters:
`x,y`: touch coordinates in parent coordinate system - as provided by on_touch_down()

:Returns: `x, y`
A value of None is returned for coordinates that are outside the Image source
'''

# get coordinates of texture in the Canvas
pos_in_canvas = self.center_x - self.norm_image_size[0] / 2., self.center_y - self.norm_image_size[1] / 2.

# calculate coordinates of the touch in relation to the texture
x1 = x - pos_in_canvas[0]
y1 = y - pos_in_canvas[1]

# convert to pixels by scaling texture_size/source_image_size
if x1 < 0 or x1 > self.norm_image_size[0]:
x2 = None
else:
x2 = self.texture_size[0] * x1/self.norm_image_size[0]
if y1 < 0 or y1 > self.norm_image_size[1]:
y2 = None
else:
y2 = self.texture_size[1] * y1/self.norm_image_size[1]
return x2, y2

然后你可以添加一个 on_touch_down() 到你的 MyImage 类:

def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
print('got a touch on', self, 'at', touch.pos, ', at image pixels:', self.to_image(*touch.pos))
return True
else:
return super(MyImage, self).on_touch_down(touch)

关于python - Kivy 获取被按下的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62000897/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com