为什么Image在Kivy中没有正确显示为Button背景?

时间:2018-01-07 18:56:51

标签: python python-3.x kivy kivy-language

我试图将这个kv代码转换为我自己的类

<BaseScreen>:     # This is GridLayout
    cols: 4
    rows: 4
    padding: 25
    Button:
        size_hint_x: None
        size_hint_y: None
        Image:
            source: "business_bookcover.png"
            x: self.parent.x
            y: self.parent.y
            width: self.parent.width
            height: self.parent.height
            keep_ratio: False

问题是我试图制作&#34;可点击的图像&#34;,但当我将小部件添加到按钮时,图像位于默认位置(0,0),完全不在按钮位置。有没有解决方法怎么做?

这是我的尝试

class Book(Button):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.size_hint = (None, None)

        book_cover_image_source = kwargs.get('cover') or BLANK_BOOK_COVER

        book_cover = Image(source=book_cover_image_source)
        book_cover.pos = self.pos
        book_cover.width = self.width
        book_cover.height = self.height
        book_cover.allow_stretch = True
        book_cover.keep_ratio = False

        self.add_widget(book_cover)

1 个答案:

答案 0 :(得分:1)

在kv语言中,将会观察到表达式(y:width:size)中使用的属性。当父级pos / class Book(Button): def __init__(self, cover=BLANK_BOOK_COVER, **kwargs): super(Book, self).__init__(**kwargs) self.size_hint = (None, None) self.book_cover = Image(source=cover) self.book_cover.allow_stretch = True self.book_cover.keep_ratio = False self.add_widget(self.book_cover) def on_size(self, *args): self.book_cover.size = self.size def on_pos(self, *args): self.book_cover.pos = self.pos 发生更改时,子窗口小部件会相应更改。您必须在Python类中提供此事件绑定:

Book

获取可点击图片的一个更简单的选择是让您的班级ButtonBehabior继承自Imagefrom kivy.uix.behaviors import ButtonBehavior from kivy.uix.image import Image class Book(ButtonBehavior, Image): def __init__(self, cover=BLANK_BOOK_COVER, **kwargs): super(Book, self).__init__(**kwargs) self.source = cover self.size_hint = (None, None) self.allow_stretch = True self.keep_ratio = False 类:

(3, 3)