Reputation: 61
I am new to GUI development, and am using Kivy
for the same. I have made a rectangle
at the top of the screen which increases/decreases its length as the size of the window changes. I want to add text inside the rectangle such that when I change the size of the window the text not only increases/decreases its font size but also stays inside the rectangle i.e in the middle. I am not able to figure out how to set the font
and position
parameters to achieve my goal.
This is the Myapp.py file code:
class Dashboard(RelativeLayout):
l = NumericProperty(0.0)
b = NumericProperty(0.0)
class MyApp(App):
def build(self):
return (Dashboard())
MyApp().run()
This is my .kv
file code:
<Dashboard>:
l: root.width
b: root.height/7
# creating Canvas
canvas:
Color:
rgba: 216 / 255., 195 / 255., 88 / 255., 1
Rectangle:
pos: (0,self.size[1]/1.15)
size: (self.l,self.b)
Label:
size: self.parent.size[0], self.parent.size[1]
font_size: self.parent.size[0] * 0.05
text_size: self.size
pos_hint: {'x':0.5,'y':0.9}
text:'hello!'
Thanks in advance! :)
Upvotes: 0
Views: 324
Reputation: 38962
The easiest way to make sure the text is centered in the Rectangle
is to make the Label
the same size and position of the Rectangle
, and then use halign
and valign
. I have added another NumericProperty
to the Dashboard
just to contain the y position of the Rectangle
and Label
, so the Dashboard
class now looks like:
class Dashboard(RelativeLayout):
l = NumericProperty(0.0)
b = NumericProperty(0.0)
ypos = NumericProperty(0)
And the modified kv
:
<Dashboard>:
l: root.width
b: root.height/7
ypos: root.size[1]/1.15
# creating Canvas
canvas:
Color:
rgba: 216 / 255., 195 / 255., 88 / 255., 1
Rectangle:
pos: (0, root.ypos)
size: (root.l,root.b)
Label:
size_hint: None, None
size: root.l, root.b
font_size: min(root.size[0] * 0.05, root.size[1] * 0.05)
text_size: self.size
halign: 'center'
valign: 'center'
pos: 0, root.ypos
text:'hello!'
I also modified the font_size
calculation so that it considers both the height and width of the Rectangle
.
Note that if you just want a colored background for the Label
you can do that within the Label
itself. Here is another version of the kv
that does that:
<Dashboard>:
l: root.width
b: root.height/7
ypos: root.size[1]/1.15
Label:
canvas.before:
Color:
rgba: 216 / 255., 195 / 255., 88 / 255., 1
Rectangle:
pos: self.pos
size: self.size
size_hint: None, None
size: root.l, root.b
font_size: min(root.size[0] * 0.05, root.size[1] * 0.05)
text_size: self.size
halign: 'center'
valign: 'center'
pos: 0, root.ypos
text:'hello!'
Upvotes: 1