Kivy-矩形延迟绑定到图像

时间:2019-06-15 19:54:30

标签: python kivy bind

我希望矩形贴在图像的左下角。它可以工作,但是当我更改窗口大小时,矩形会稍微关闭。这是更新之前映像的位置。这是代码:

from kivy.app import App, Builder
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.graphics import Rectangle
from kivy.graphics import Color


Builder.load_string(
'''
<Screen>:
    canvas.before:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size
    FloatLayout:
        Image:
            id: im
            keep_data: True
            source: 'test.png'
            allow_stretch: True
            size_hint_y: 0.9
            pos_hint: {'left':1, 'top':1}
        Button:
            text: 'Button'
            size_hint_y: 0.1
            pos_hint: {'x':0, 'y':0}
''')


class Screen(FloatLayout):
    def __init__(self, **kwargs): 
        super(Screen, self).__init__(**kwargs) 
        with self.ids.im.canvas.after:
            Color(1,0,1,.5) 
            self.rec = Rectangle(pos=(self.ids.im.center_x - self.ids.im.norm_image_size[0] / 2,
                                      self.ids.im.center_y - self.ids.im.norm_image_size[1] / 2),
                                 size=(self.ids.im.norm_image_size[0]/2,
                                       self.ids.im.norm_image_size[1]/2))
        self.bind(pos=self.update_canvas, size=self.update_canvas)

    def update_canvas(self, *args):
        self.rec.pos = (self.ids.im.center_x - self.ids.im.norm_image_size[0] / 2,
                        self.ids.im.center_y - self.ids.im.norm_image_size[1] / 2)
        self.rec.size = (self.ids.im.norm_image_size[0]/2,
                         self.ids.im.norm_image_size[1]/2)


class QuestionApp(App):
    def build(self):
        return Screen()

if __name__ == "__main__":
    QuestionApp().run()

我在Python中执行此操作是因为我想在图像中随机生成矩形,但是当窗口调整大小时,我被矩形卡住了。

1 个答案:

答案 0 :(得分:1)

如果您希望矩形使用图像的几何图形作为参考,则必须对此图像进行绑定:

self.bind(pos=self.update_canvas, size=self.update_canvas)

self.ids.im.bind(pos=self.update_canvas, size=self.update_canvas)