Caa*_*los 3 python python-3.x kivy kivy-language
如何在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
Run Code Online (Sandbox Code Playgroud)
如何将TextInput的文本居中?
Key*_*Usr 11
Afaik,没有像对待那样对齐的东西Label,但是,你可以用它padding来推动你想要的位置.请记住,更改文本大小会影响居中,因此您需要重新计算大小的变化(例如,在处理多个设备,大小等时).
或者甚至可以有一个解决方法,你可以使其TextInput隐藏,用于Label获取触摸事件来触发TextInput(这将打开键盘)并更改文本属性Label更改时TextInput的文本.你将失去以这种方式使用光标的可能性,你将需要处理包装文本.
例:
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()
Run Code Online (Sandbox Code Playgroud)
self._get_text_width(...)显然是一种方法TextInput.它正在使用小部件的核心,所以它可能不稳定(我发布的第一个例子是因为我的错误而错误)^^
现在,如果padding_x从left和中填充的值right,你只需要左侧(区别仅在于在正确的位置使用加法和减法),所以让我们这样做:
TextInputcenter[0]坐标减去当我们已经将X轴居中时,让我们转到Y. padding_y的值是top和bottom:
heightTextInputself.height / 2.00,我们不关心它注意:max()期望一些参数,如果没有text,max()将提高其声音.我们将使用另一个左侧填充来关闭它以padding_x仅使用中心:
<padding_x with max> if self.text else [self.center[0], 0]
Run Code Online (Sandbox Code Playgroud)
小智 6
@pete halign:“center”加上 y 轴上的填充也只能完成这项工作
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<Test>:
TextInput:
text: 't'
halign: 'center'
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()
Run Code Online (Sandbox Code Playgroud)