如何使用pos_hint在floatlayout中定位kivy小部件



我一直在尝试使用pos_hint在FloatLayout中的kivy中定位小部件。如果标签从一开始就存在,例如,如果我可以在.kv文件中定义pos_hint,那么一切都会按预期进行。不过,我稍后会尝试创建按钮。使用这个.kv文件(名为layouttest.kv(:

<NewButton@Button>:
size_hint: (0.1, 0.1)
<BasicFloatLayout@FloatLayout>:
Button:
size_hint: (0.4, 0.2)
pos_hint: {'x': 0.0, 'top': 1.0}
text: 'create Button'
on_release: self.parent.create_Button()

在这个python代码中,我试图将新创建的空白按钮放置在BasicFloatLayout大小的0%-100%的随机y位置,以及0-200px的随机x位置。如果我按下一次按钮,一切都如预期。第二次按下时,第一个创建的按钮将改变其y位置,使其与新创建的按钮相同。第三次按下时,两个旧按钮将与新创建的按钮对齐,依此类推。然而,x位置将保持不变。有人能解释一下我在这里做错了什么吗?(如果你能帮助我使用更新功能和pos_hint移动按钮,则可获得额外积分(

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.properties import NumericProperty 
from kivy.clock import Clock
import random
class BasicFloatLayout(FloatLayout):
timer = NumericProperty(0)
def update(self, *args):
self.timer += 1
for child in self.children:
try: child.update()
except AttributeError:
pass
def create_Button(self):
button = NewButton( (random.random(), random.random()) )
self.add_widget(button)

class NewButton(Button):
def __init__(self, pos, **kwargs):
super(NewButton, self).__init__(**kwargs)
self.pos[0] = 200*pos[0]
self.pos_hint['y'] = pos[1]
class layouttestApp(App):
def build(self):
GUI = BasicFloatLayout()
Clock.schedule_interval(GUI.update, 1/30.)
return GUI
if __name__ == "__main__":
layouttestApp().run()

首先,使pos_hint: {'x': 0.0, 'y': 0.5}(因为很难让两个不同的东西工作,如果您使用x,请使用y而不是Top,如果您正在使用Top,则使用x的Bottom insead(

其次,不要在kv文件中给出on_release: self.parent.create_Button(),而是这样做:on_release: root.create_Button()

第三,您只为y值赋值,还应该为x值赋值,行是NewButton类中的self.pos_hint['y'] = pos[1]

但你可以通过这样做让它变得更简单:

#from your first class......
def create_Button(self):
button = NewButton(self.pos_hint{'x' : random.random(), 'y' : random.random()}
self.add_widget(button)
class NewButton(Button):
def __init__(self, *kwargs):
pass

希望这是有意义的,你可以修改更多。(注意:我还没有写你主要课程的开头部分,我很懒;-p(

最新更新