我想获取FloatLayout
的中心(或顶部等)坐标。通过使用on_touch_up
事件,我做得很好,但在__init__
部分却无法获得它。
如何修改我的代码以获取center_1
?
我尝试了to_local
,to_window
,to_parent
,但是我做得不好...
import kivy
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.floatlayout import FloatLayout
class TestLayer(FloatLayout):
def __init__(self, **kwargs):
super(TestLayer, self).__init__(**kwargs)
self.pos_hint = {'top':1, 'x':0}
self.size_hint_x = 1
self.size_hint_y = 1
print('center_0 : %s, %s' % (self.center_x, self.center_y))
# >> center_0 : 50, 50
# How to get 'center_1' at this def without using 'on~' event?
def on_touch_up(self, touch):
if self.collide_point(*touch.pos):
if touch.button == 'left':
print('center_1 : %s, %s' % (self.center_x, self.center_y))
# >> center_1 : 400, 300
return super(TestLayer, self).on_touch_up(touch)
class TestScreen(Screen):
def __init__(self, **kwargs):
super(TestScreen, self).__init__(**kwargs)
layer = TestLayer()
self.add_widget(layer)
sm = ScreenManager()
class DemoApp(App):
def build(self):
sm.add_widget(TestScreen(name='test'))
return sm
if __name__ == '__main__':
DemoApp().run()
答案 0 :(得分:1)
小部件的位置和大小在__init__()
方法中仍是默认值,并且这些值在显示小部件之前无用。显示窗口小部件后,可以使用Clock.schedule_once()
运行方法。因此,您可以通过对TestLayer
进行一些更改来获取此信息:
class TestLayer(FloatLayout):
def __init__(self, **kwargs):
super(TestLayer, self).__init__(**kwargs)
self.pos_hint = {'top':1, 'x':0}
self.size_hint_x = 1
self.size_hint_y = 1
print('center_0 : %s, %s' % (self.center_x, self.center_y))
# >> center_0 : 50, 50
# How to get 'center_1' at this def without using 'on~' event?
Clock.schedule_once(self.get_coords, 1)
def get_coords(self, dt):
print('center_2 : %s, %s' % (self.center_x, self.center_y))
Clock.schedule_once(self.get_coords, 1)
安排在1秒钟内呼叫get_coords
。
不使用kivy.clock
来获取坐标的另一种方法是使第一个Screen
成为虚拟对象,然后切换到“测试” Screen
,然后使用{{1} }方法:
on_enter