我正在制作gui应用程序,出于美观原因,我想随机生成带有彩色背景的标签。
但是,每当生成标签时,画布矩形都会停留在左下角。
pos_hint仅影响Rectangle,而pos_hint指示将文本移动到的矩形。
代码:
import kivy
import random
from kivy.app import App
from kivy.uix.label import Label
from kivy.graphics import Color, Rectangle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
class BackgroundLines(Label):
def on_size(self, *args):
self.canvas.before.clear()
with self.canvas.before:
Color(.2, .3, .4, 1)
Rectangle(pos=self.pos, size=self.size)
class widget(FloatLayout):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
with self.canvas.before:
Color(1, 1, 1, .5)
Rectangle(pos=self.pos, size=self.size)
n1 = random.randint(20, 65) / 100
n2 = random.randint(20, 65) / 100
b1 = Button(pos_hint={'x': 0, 'center_y': .5}, size_hint=(.3, .2))
b2 = BackgroundLines(text='hidasd',size_hint=(.5, .2),pos_hint = {'x': n1, 'y': n2})
self.add_widget(b1)
self.add_widget(b2)
class TestApp(App):
def build(self):
return widget()
if __name__ == '__main__':
TestApp().run()
答案 0 :(得分:2)
完成所需操作的最简单方法是使用kv
。例如:
class BackgroundLines(Label):
rgba = ListProperty([0.5, 0.5, 0.5, 1])
Builder.load_string('''
<BackgroundLines>:
canvas.before:
Color:
rgba: self.rgba
Rectangle:
pos: self.pos
size: self.size
''')
那么您可以做:
b2 = BackgroundLines(text='hidasd',size_hint=(.5, .2),pos_hint = {'x': n1, 'y': n2}, rgba=[1, 0, 0, 1])
和:
b2.rgba = [0,0,1,1]