[英]How to resize automatically the text from a widget(button/label) when i resize the window in kivy with the mouse
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.我是 py 和 kv 的初学者,我试图弄清楚如何在 label 或一个按钮在我调整黑色 kivy Z05B8C74CBD96FBF2DE4C1A352702FFF4 的大小时自动调整大小。
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.最简单的方法是使用
kv
语言,您可以将字体大小指定为 window 大小的 function。 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.要在 Python 中完成同样的事情,您可以实现
kv
语言将为您做的事情。 You can implement an on_size()
method in the QuizzWindow
class that gets called whenever the size
of the QuizzWindow
changes.您可以在
QuizzWindow
class 中实现on_size()
方法,只要QuizzWindow
的size
发生变化,就会调用该方法。 Then, in that method you can adjust the font_size
of the Label
and Button
.然后,在该方法中,您可以调整
font_size
和Button
的Label
。 Of course, to do that, you must have a reference to the Label
and Button
.当然,要做到这一点,您必须参考
Label
和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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.