ScatterLayout - do_translation không hoạt động

Nov 03 2020

Mã của tôi

import kivy
from kivy.uix.scatterlayout import ScatterLayout
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button

class MyScatter(ScatterLayout):

    def __init__(self, *args, **kwargs):
        super(MyScatter, self).__init__(*args, **kwargs)
        self.img = Image(source='img.png', keep_ratio=True, center = self.center)
        self.add_widget(self.img)

class MainApp(App):
    def build(self):
        mainbox = FloatLayout()
        mainbox.add_widget(Button(text="Prev",
                                  font_size="17dp",
                                  size_hint=(.15, .15),
                                  pos_hint={"left":1,
                                            "center_y":0.5},
                                  ))
        ms = MyScatter(scale=1, pos_hint={"center_x":0.33, "center_y":0.5}, do_scale = True, do_rotation = False, do_translation = True)
        mainbox.add_widget(ms)
        return mainbox

root = MainApp()
root.run()

Vị trí của nút và hình ảnh là theo nhu cầu của tôi. Nhưng, tôi đã định nghĩa do_translation= True cho MyScattervà nó không hoạt động.

Trả lời

xralf Nov 03 2020 at 03:24

Tôi lấy cảm hứng từ đây và viết mã này:

import kivy
from kivy.uix.scatterlayout import ScatterLayout
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button

class MyScatter(ScatterLayout):

    def __init__(self, *args, **kwargs):
        super(MyScatter, self).__init__(*args, **kwargs)
        self.img = Image(source='img.png', keep_ratio=True, pos_hint={"center_x":0.33, "center_y":0.5})
        self.add_widget(self.img)

    def on_touch_move(self, touch): #magic time!!!!
       res =  super(MyScatter, self).on_touch_move(touch)
       if res: #Yay do something!
           self.img.pos = (self.center_x, self.center_y)
       return res

class MainApp(App):
    def build(self):
        mainbox = FloatLayout()
        mainbox.add_widget(Button(text="Prev",
                                  font_size="17dp",
                                  size_hint=(.15, .15),
                                  pos_hint={"left":1,
                                            "center_y":0.5},
                                  ))
        ms = MyScatter(scale=1, do_scale = True, do_rotation = False, do_translation = True)
        mainbox.add_widget(ms)
        return mainbox

root = MainApp()

root.run()

Nó dường như hoạt động. Xin vui lòng, cho tôi biết nếu nó là giải pháp tốt.