如何使用pos_提示在floatlayout中定位kivy小部件?

2024-05-31 23:40:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试使用pos_提示将kivy中的小部件定位到FloatLayout中。 如果标签从一开始就存在,例如,如果我可以在.kv文件中定义pos_提示,那么一切都会按预期进行。不过,我稍后会尝试创建按钮。使用此.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代码中,我试图将新创建的空白按钮放置在一个随机的y位置,范围为基本浮动窗口大小的0%-100%,以及一个随机的x位置,范围为0-200px。 如果我按下按钮一次,一切都会按预期进行。第二次按下时,第一个创建的按钮将更改其y位置,使其与新创建的按钮相同。第三次按下时,两个旧按钮将与新创建的按钮对齐,依此类推。然而,x定位仍将如预期的那样。有人能解释一下我做错了什么吗? (如果您可以使用更新功能和pos_提示帮助我移动按钮,则可获得额外积分)

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()

Tags: fromposimportselfdefcreatebuttonrandom
1条回答
网友
1楼 · 发布于 2024-05-31 23:40:05

首先,使pos_hint: {'x': 0.0, 'y': 0.5}(因为很难让两种不同的东西工作,如果使用x,则使用y而不是Top,如果使用Top,则使用x的底部插入部分)

其次,不要在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)

相关问题 更多 >