3
如何在矩形內添加文本?我正在使用下面的代碼,並在畫布中添加了一個標籤,希望它會顯示在矩形內。python kivy在矩形內添加文本
import kivy
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.video import Video
from kivy.uix.relativelayout import RelativeLayout
from kivy.graphics import *
class MyApp(App):
def build(self):
r = AnchorLayout()
f = RelativeLayout()
g = GridLayout(cols=3, rows=5)
v = Video(source='driver.mp4', state='play', options={'eos':'loop'})
l1 = Label(text="jenkins", font_size=32)
l2 = Label(text="git", font_size=32)
f.add_widget(v)
f.add_widget(g)
g.add_widget(l1)
g.add_widget(l2)
with g.canvas:
Color(.4, .1, .1)
Rectangle(pos=(100,10), size=(100,100))
Label(text="KSHK")
return f
if __name__ == "__main__":
MyApp().run()
更新: 在ColoredLabel
import kivy
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.video import Video
from kivy.uix.relativelayout import RelativeLayout
from kivy.graphics import *
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from random import random
from kivy.properties import ListProperty
kv = '''
<ColoredLabel>:
background_color:
canvas.before:
Color:
rgba: self.background_color
Rectangle:
pos: (10,10)
size: (100,100)
'''
Builder.load_string(kv)
class ColoredLabel(Label):
background_color = ListProperty((0,0,0,1))
class MyApp(App):
def build(self):
f = AnchorLayout()
g = GridLayout(cols=2, rows=2)
layout = BoxLayout(size_hint=(1, None), height=50)
v = Video(source='driver.mp4', state='play', options={'eos':'loop'})
l1 = Label(text="jenkins", font_size=32)
l2 = Label(text="git", font_size=32)
f.add_widget(v)
label = ColoredLabel(text="Hello World!", background_color=(random(), random(), random(), 1))
g.add_widget(label)
f.add_widget(g)
return f
if __name__ == "__main__":
MyApp().run()
我試過這個方法,但是當我在AnchorLayout/Relative佈局的頂部添加布局部件時,文本沒有在框中居中...... – krisdigitx
感謝Nykakin,這個工作.. – krisdigitx