在Kivy中使TextInput在BoxLayout居中
这是我kivy应用程序的截图。我想把左下角的TextInput
放在它所在的BoxLayout
的正中间,但我不想让它和布局一样大,我希望它小一些。这个BoxLayout
在屏幕的下半部分。我尝试过设置TextInput
的属性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
1 个回答
4
你给了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的中心位置。