上面代码报错 AttributeError: 'MyScatter' object has no attribute 'touches'
时间: 2023-06-21 12:15:24 浏览: 48
非常抱歉,我之前的代码有误。在 `kivy` 中,`MyScatter` 对象的 `touches` 属性是一个字典,而不是一个列表。因此,我们需要使用 `values()` 方法来获取所有手指的位置信息。下面是修改后的代码:
```
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.scatter import Scatter
class MyScatter(Scatter):
def __init__(self, **kwargs):
super(MyScatter, self).__init__(**kwargs)
self.last_pinch_distance = 0
def on_touch_down(self, touch):
if len(self.touches) == 2:
x1, y1 = next(iter(self.touches.values())).pos
x2, y2 = next(iter(self.touches.values(), offset=1)).pos
self.last_pinch_distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
return super(MyScatter, self).on_touch_down(touch)
def on_touch_move(self, touch):
if len(self.touches) == 2:
x1, y1 = next(iter(self.touches.values())).pos
x2, y2 = next(iter(self.touches.values()), offset=1).pos
current_pinch_distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
pinch_distance_delta = current_pinch_distance - self.last_pinch_distance
if pinch_distance_delta < 0:
self.scale -= 0.01
elif pinch_distance_delta > 0:
self.scale += 0.01
self.last_pinch_distance = current_pinch_distance
return super(MyScatter, self).on_touch_move(touch)
class ImageApp(App):
def build(self):
scatter = MyScatter()
image = Image(source='image.jpg')
scatter.add_widget(image)
return scatter
if __name__ == '__main__':
ImageApp().run()
```
在这个修改后的程序中,我们使用了 `values()` 方法来获取所有手指的位置信息,并使用 `offset` 参数来获取第二个手指的位置信息。这样,我们就可以正确地计算两个手指之间的距离了。
再次感谢您指出错误,希望这次能够帮到您。