我想在 Kivy 中用红色矩形覆盖一个按钮。此按钮位于BoxLayout. 我已经定义MyButton了在按钮上绘制矩形的类,它可以工作。但是,如果我固定BoxLayout按钮所在的宽度,矩形会转到左下角。
MWE:
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.graphics import Color, Rectangle
Builder.load_string('''
<MainApp>:
orientation: 'horizontal'
BoxLayout:
orientation: 'vertical'
# width: 100 # uncommenting these two lines breaks the rectangle positioning
# size_hint: (None,1)
MyButton:
text: 'button1'
size_hint: (1,None)
height: 50
Label:
Label:
''')
class MyButton(Button):
def __init__(self, **kwargs):
super(MyButton, self).__init__(**kwargs)
def on_size(self, *args):
self.canvas.after.clear()
with self.canvas.after:
Color(1, 0, 0, 1)
Rectangle(pos=self.pos, size=self.size)
class MainApp(BoxLayout):
pass
class TestApp(App):
def build(self):
return MainApp()
if __name__ == '__main__':
TestApp().run()
取消注释中的两条注释行Builder.load_string会破坏矩形定位。我错过了什么?
www说
相关分类