Kivy中如何装饰EventDispatcher的setter函数实现Image按比例缩放?
KV语言实现效果示例
以下KV代码实现了Button内嵌套Image,并让Image尺寸始终保持为Button的1/4比例:
Button: text:'Katze' background_color: ('#00ffff') font_size: 32 on_press:root.playSound(self) Image: source: './katze.png' center_x: self.parent.center_x center_y: self.parent.center_y size: root.width*0.25, root.height*0.25
问题与当前近似方案
希望在Python代码中复现上述效果,当前已实现Image随Button居中,但直接绑定size会让Image和Button同尺寸,不符合需求:
def build(self): self.layout = GridLayout(cols=3, spacing=10) for animal in self.zoo: knopf = ButtonID( id = animal, # ButtonID继承自Button background_color=get_color_from_hex(self.zoo[animal][0]), on_press = self.playSound, ) self.layout.add_widget(knopf) bild=Image() knopf.add_widget(bild) bild.source=self.animal[tier][2] knopf.bind(center=bild.setter('center')) # 原绑定方式会让Image和Button同尺寸,不符合要求 # knopf.bind(size=bild.setter('size')) return self.layout
解决方案:自定义绑定回调(无需装饰器)
不用装饰器,直接写一个回调函数,在Button尺寸变化时,主动将Image尺寸设为Button的1/4比例。这种方式更直观,适合新手理解:
- 先定义一个回调函数,接收Button实例和新的尺寸值:
def update_image_size(self, button, new_size): # 将Image尺寸设为Button尺寸的1/4 bild = button.children[0] # 假设Image是Button的第一个子控件 bild.size = (new_size[0] * 0.25, new_size[1] * 0.25)
- 修改build函数中的绑定逻辑,替换原来的size绑定:
def build(self): self.layout = GridLayout(cols=3, spacing=10) for animal in self.zoo: knopf = ButtonID( id = animal, background_color=get_color_from_hex(self.zoo[animal][0]), on_press = self.playSound, ) self.layout.add_widget(knopf) bild=Image() knopf.add_widget(bild) bild.source=self.animal[tier][2] knopf.bind(center=bild.setter('center')) # 绑定到自定义回调函数,实现比例缩放 knopf.bind(size=self.update_image_size) return self.layout
补充说明
- 这里没有用装饰器,因为对于新手来说,直接写绑定回调的逻辑更清晰,不需要理解装饰器的函数包装、参数传递等复杂概念。
- 如果Button内有多个子控件,不要用
button.children[0],可以给Image设置id或者在创建时把Image和Button关联起来(比如用字典存储),避免找错控件。
内容的提问来源于stack exchange,提问作者michaD
相关产品推荐
相关产品推荐

