[英]How to draw a rectangle over a button with fixed width in Kivy?
I want to cover a button with a red rectangle in Kivy.我想在 Kivy 中用红色矩形覆盖一个按钮。 This button stands in a BoxLayout
.此按钮位于BoxLayout
中。 I have defined the MyButton
class that draws a rectangle over a button and it works.我已经定义了MyButton
class ,它在按钮上绘制一个矩形并且它可以工作。 However, if I fix the width of the BoxLayout
the button is in, the rectangle goes to the bottom left corner.但是,如果我固定按钮所在的BoxLayout
的宽度,则矩形会转到左下角。
MWE: 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()
Uncommenting the two commented lines in Builder.load_string
breaks the rectangle positioning.取消注释Builder.load_string
中的两条注释行会破坏矩形定位。 What am I missing?我错过了什么?
In your MyButton
class, you have a on_size()
method, but no on_pos()
method.在您的MyButton
class 中,您有一个on_size()
方法,但没有on_pos()
方法。 I think you just need to add that method:我认为您只需要添加该方法:
def on_pos(self, *args):
self.on_size()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.