不知何故,我不知道是否可以在 KivyMD 的按钮换行中制作长文本。
在经典的 Kivy 中,这是通过“text_size: self.width, None”完成的
但是在 KivyMD 中,无论我做什么,结果仍然是一行,没有任何结束。
有人知道怎么做吗?
我的尝试: KV文件:
MDScreen:
name: 'wrap'
md_bg_color: app.theme_cls.bg_darkest
MDBoxLayout:
orientation:'vertical'
size_hint: .9, .66
pos_hint: {'center_x': .5, 'center_y': .5 }
MDRaisedButton:
text: 'asdlkasjdlaskjda asdlkasjdlaskjda aslkdjaskldjasd aslkdjaslkdjasld asldkjasldkjasd'
size_hint_y: None
text_size: self.width, None
size_hint: .3, .12
pos_hint: {'center_x': .5, 'center_y': .33 }
PY文件:
from kivy.lang import Builder
from kivymd.uix.screen import MDScreen
from kivymd.app import MDApp
from kivy.uix.screenmanager import ScreenManager
from kivymd.toast import toast
from random import randint
class MainLayout(MDScreen):
pass
class MyApp(MDApp):
def build(self):
self.screen_manager = ScreenManager()
self.screen_manager.add_widget(Builder.load_file('wrap.kv'))
return self.screen_manager
MyApp().run()
我认为这是 kivymd 的一个特性,但你可以扩展
MDRaisedButton
通过编写你自己的文本换行方法来做你想做的事。这是一个简单的例子,但实际的类会复杂得多:
class MyMDRaisedButton(MDRaisedButton):
ignore_text_change = BooleanProperty(False)
def on_text(self, instance, new_text):
# this ignores the text change that this code performs
# in order to avoid an infinite loop
if self.ignore_text_change:
self.ignore_text_change = False
return
# this code does the wrapping
replacement_text = ''
for ch in new_text:
if ch == ' ':
replacement_text += '\n'
else:
replacement_text += ch
# set the ignore boolean
self.ignore_text_change = True
# replace the original text with the wrapped text
self.text = replacement_text