这是我的 kivy 应用程序的屏幕截图。我试图让左下角的 TextInput
在它所在的 BoxLayout
中居中,我不希望它与布局,我希望它小得多。有问题的 BoxLayout
位于屏幕的下半部分。我已经尝试设置 TextInput
的属性center:self.parent.center
但这不起作用。如您所见,我使用那一行 self.parent.center 将中心坐标从 BoxLayout
打印到 TextInput
中,结果正确。然而,将 TextInput
的中心或位置设置为这些坐标并没有使它居中,它也没有移动……我做错了什么?
py文件:
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
class TimeTabler(Widget):
pass
class TimerApp(App):
def build(self):
return TimeTabler()
if __name__ == "__main__":
TimerApp().run()
****kv文件:****
#:kivy 1.0
BoxLayout:
orientation: 'vertical'
size: root.size
BoxLayout:
orientation: 'vertical'
Label:
text: 'TimeTabler'
BoxLayout:
TextInput:
text: '%s' % (self.parent.center) # why does this work here
size_hint: None, None
width: sp(200)
height: sp(30)
center: self.parent.center # but not here
最佳答案
您给了 TextInput size_hint: None, None
,因此 BoxLayout 不会尝试手动给它正确的大小,它假定默认大小为 100, 100
。只需删除 size_hint
行即可修复它。
此外,一些小部件具有类似 size: self.size
的行。这是没有意义的,self
指的是小部件本身,显然该行什么也没做,因为它只是试图将大小设置为它已经存在的大小。
如果您让 TimeTabler 继承自 BoxLayout 而不是 Widget,事情也会变得更简单。这样您就不需要手动设置它的子 BoxLayout 的大小。
编辑:看来我误解了你的意思,下面是一个使用 AnchorLayout 使 TextInput 居中的示例:
<TimeTabler>
BoxLayout:
orientation: 'vertical'
size: root.size
on_touch_down: print self.pos, self.size
canvas:
Color:
rgba: 0, 1, 1, .3
Rectangle:
size: self.size
pos: self.pos
BoxLayout:
orientation: 'vertical'
size: self.size
Label:
text: 'TimeTabler'
BoxLayout:
id: bl
on_touch_down: print 'center', self.center
canvas:
Color:
rgb: 1,1,1
Line:
rectangle: self.x, self.y, self.width, self.height
AnchorLayout:
TextInput:
size_hint: None, None
text: '%s, %s' % (self.get_center_x(), self.get_center_y())
我认为您的问题是 BoxLayout 会自动设置 TextInput 的位置,即使它正在设置自己的大小时也是如此。解决此问题的一个简单方法是紧挨着另一个小部件中的 TextInput,在本例中是一个 AnchorLayout,它负责为您居中。您也可以只使用 Widget 和之前设置 TextInput 中心的机制。
关于python - 在 Kivy 的 BoxLayout 中居中 TextInput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22821706/