I am a beginner to py and kv and i try to figure out how to make the text inside a label or a button to resize automatically when i resize the black kivy window.
import kivy
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.app import App
class QuizzWindow(BoxLayout):
def __init__(self, **kwargs):
super(QuizzWindow, self).__init__(**kwargs)
self.cols = 1
self.add_widget(Label(text="quizz"))
self.add_widget(Button(text="press"))
class MyApp(App):
def build(self):
return QuizzWindow()
if __name__ == "__main__":
MyApp().run()
Thanks for your help !
The simplest way is to use the kv
language where you can specify the font size as a function of the window size. Here is a modified version of your code that does it:
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
kv = '''
<QuizzWindow>:
Label:
text: 'quizz'
font_size: root.height/15
Button:
text: 'press'
font_size: root.height/15
'''
class QuizzWindow(BoxLayout):
pass
class MyApp(App):
def build(self):
Builder.load_string(kv)
return QuizzWindow()
if __name__ == "__main__":
MyApp().run()
To accomplish the same thing in just Python, you can implement what the kv
language would do for you. You can implement an on_size()
method in the QuizzWindow
class that gets called whenever the size
of the QuizzWindow
changes. Then, in that method you can adjust the font_size
of the Label
and Button
. Of course, to do that, you must have a reference to the Label
and Button
. Here is a modified version of your code that does it:
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.app import App
class QuizzWindow(BoxLayout):
def __init__(self, **kwargs):
super(QuizzWindow, self).__init__(**kwargs)
self.label = Label(text="quizz") # save a reference
self.button = Button(text="press") # save a reference
self.add_widget(self.label)
self.add_widget(self.button)
def on_size(self, *args):
# called when size changes
self.label.font_size = self.height / 20
self.button.font_size = self.height / 20
class MyApp(App):
def build(self):
return QuizzWindow()
if __name__ == "__main__":
MyApp().run()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.