我正在尝试将此 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
问题是我正在尝试制作“可点击图像”,但是当我将小部件附加到按钮时,图像位于默认位置(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)
最佳答案
在 kv languaje 表达式中使用的属性 (x:
, y:
, width:
) 将被观察到。当父级的 size
/pos
更改时,子级 widget 也会相应更改。您必须在 Python 类中提供此事件绑定(bind):
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
获取可点击图像的一个更简单的选择是让您的类 Book
继承 ButtonBehabior
和 Image
类:
from 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
关于python - 为什么图像在 Kivy 中不能正确显示为按钮背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48140520/