[英]Kivy TextInput horizontal and vertical align (centering text)
如何在Kivy的TextInput中水平居中文本?
這是我的kv語言的一部分:
BoxLayout:
orientation: 'vertical'
Label:
markup: True
text: '[b] Type something... [/b]'
size_hint: 1, 0.6
size: self.parent.size[0], 200
font_size: self.size[0] * 0.1
text_size: self.size
halign: 'center'
valign: 'middle'
canvas.before:
Color:
rgb: 0, 0, 204
Rectangle:
pos: self.pos
size: self.size
TextInput:
focus: True
如何將TextInput的文本居中?
Afaik,沒有像Label
那樣對齊的東西,但是,你可以使用padding
來推動任何你想要的位置。 請記住,更改文本大小會影響居中,因此您需要重新計算大小的變化(例如,在處理多個設備,大小等時)。
或者甚至可以有一個解決方法,你可以使TextInput
不可見,使用Label
來獲取觸摸事件來觸發TextInput
(這將打開鍵盤)並在TextInput
的text屬性更改時更改Label
的文本。 你將失去以這種方式使用光標的可能性,你將需要處理包裝文本。
例:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<Test>:
TextInput:
text: 't'
font_size: 60
# left, right
padding_x:
[self.center[0] - self._get_text_width(max(self._lines, key=len), self.tab_width, self._label_cached) / 2.0,
0] if self.text else [self.center[0], 0]
# top, bottom
padding_y: [self.height / 2.0 - (self.line_height / 2.0) * len(self._lines), 0]
''')
class Test(BoxLayout):
pass
class TestApp(App):
def build(self):
return Test()
TestApp().run()
self._get_text_width(...)
顯然是TextInput
一種方法。 它正在使用小部件的核心,所以它可能不穩定(我發布的第一個例子是因為我的錯誤而錯誤)^^
現在,如果padding_x
的值從left
和right
padding_x
,您只需要左側(區別僅在於在正確的位置使用加法和減法),所以讓我們這樣做:
TextInput
最長的子字符串 center[0]
坐標減去 當我們已經將X軸居中時,讓我們轉到padding_y
的值是top
和bottom
:
height
的一半 TextInput
的行數 self.height / 2.0
減去數字 0
,我們不關心它 注意: max()
需要一些參數,如果沒有text
, max()
會提高聲音。 我們將與替代左填充關閉它padding_x
只使用中心:
<padding_x with max> if self.text else [self.center[0], 0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.