请告诉我如何将这个按钮特定的kivy语言脚本转换为仍然使用kivy的纯python

2024-04-26 21:54:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下python代码:

# (other imports)
from kivy.uix.image import Image

class ChessCell(Button):
    pass

&;此Kivy语言脚本:

<ChessCell>:
    set_hint: None, None
    Image:
        set_hint: None, None
        allow_stretch: True
        keep_ratio: False
        y: self.parent.y - (self.parent.height - self.height)/2
        x: self.parent.x
        height: self.parent.height 
        width: self.parent.width

我想将这个Kivy语言脚本翻译成纯python,仍然使用Kivy库。 到目前为止,我已经做到了:

class ChessCell(Button):  
    def __init__(self, **kwargs):
        super(ChessCell, self).__init__(**kwargs)
        self.size_hint_x = None
        self.size_hint_y = None

但我不知道该怎么做:

    Image:
        set_hint: None, None
        allow_stretch: True
        keep_ratio: False
        y: self.parent.y - (self.parent.height - self.height)/2
        x: self.parent.x
        height: self.parent.height 
        width: self.parent.width

这一定很简单,但我看不出来。有人能告诉我如何转换这个吗


1条回答
网友
1楼 · 发布于 2024-04-26 21:54:42

这比你想象的要复杂一些。当您使用kivy语言时,会为您创建python绑定。在您的示例中,将为Imagepossize创建绑定。下面是一些代码,我认为它们符合您的要求:

class ChessCell(Button):
    def __init__(self, **kwargs):
        self.img = Image(allow_stretch=True, keep_ratio=True)
        super(ChessCell, self).__init__(**kwargs)
        self.add_widget(self.img)
        self.size_hint = (None, None)

    def on_pos(self, *args):
        # sets position of Image
        self.img.x = self.x
        self.img.y = self.y - (self.height - self.img.height) / 2

    def on_size(self, *args):
        # sets size of Image
        self.img.size = self.size

相关问题 更多 >