我是py和kv的初学者,当我调整黑色kivy窗口的大小时,我试图弄清楚如何使标签或按钮内的文本自动调整大小。
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()
谢谢你的帮助!
最简单的方法是使用kv
语言,您可以将字体大小指定为窗口大小的函数。以下是您代码的修改版本:
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()
要在Python中完成同样的事情,您可以实现kv
语言将为您做的事情。您可以在QuizzWindow
类中实现on_size()
方法,只要QuizzWindow
的size
发生更改,就会调用该方法。然后,在该方法中,您可以调整Label
和Button
的font_size
。当然,要做到这一点,您必须引用Label
和Button
。以下是您代码的修改版本:
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()