![](/img/trans.png)
[英]How can i prevent my label from stretching when i resize the window in kivy?
[英]How to resize automatically the text from a widget(button/label) when i resize the window in kivy with the mouse
我是 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()
謝謝你的幫助 !
最簡單的方法是使用kv
語言,您可以將字體大小指定為 window 大小的 function。 這是執行此操作的代碼的修改版本:
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
class 中實現on_size()
方法,只要QuizzWindow
的size
發生變化,就會調用該方法。 然后,在該方法中,您可以調整font_size
和Button
的Label
。 當然,要做到這一點,您必須參考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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.