更改标签在Kivy中的位置

问题描述

我是猕猴桃编程的新手,虽然似乎有很多有关此问题的在线文档,但我似乎一点都不了解,希望可以为您提供帮助。

我有4个按钮和一个标签,通过按这些按钮,我希望沿该方向移动标签。 我有两个变量pX和pY,它们是标签的位置,并希望每次更新这两个变量时都更新其位置。 预先感谢。

// main.py
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle,Color
from kivy.core.window import Window
from kivy.config import Config
from kivy.uix.floatlayout import FloatLayout

Window.size = (900,600)
Config.set('graphics','resizable',True)


class FloatLayout(FloatLayout):
    pX = 0.6
    pY = 0.1


class FenetreApp(App):
    def build(self):
        return FloatLayout()


FenetreApp().run()
//fenetre.kv
<Button>:
     size_hint: 0.1,0.1
     background_color: 0.1,0.5,0.6,1


<Label>:
     size_hint: 0.1,0.1
     background_color: 1,1
     canvas.before:
          Color:
               rgb: 0.1,0
          Rectangle:
               pos: self.pos
               size: self.size

<FloatLayout>:
     Button:
          text: "Up"
          pos_hint: {"x":0.8,"top":1}
          on_press: root.pY= root.pY +0.1
     Button:
          text: "Down"
          pos_hint: {"x":0.8,"top":0.8}
          on_press: root.pY= root.pY -0.1
     Button:
          text: "Left"
          pos_hint: {"x":0.7,"top":0.9}
          on_press: root.pX= root.pX -0.1
     Button:
          text: "Right"
          pos_hint: {"x":0.9,"top":0.9}
          on_press: root.pX= root.pX +0.1


     Label:
          name: "L1"
          text: "I wanna move"
          pos_hint: {"x":root.pY,"top":root.pY} ```

解决方法

您需要使用NumericProperty作为数值,否则kivy不会更新其自己的子位置,文本和其他内容,但是如果您不想使用'em',请检查此代码。我希望它能清楚地了解其工作原理: main.py:

from kivy.app import App
from kivy.core.window import Window
from kivy.lang import Builder
Window.size = (900,600)
kv = Builder.load_string('''
FloatLayout:
    pY: .5
    pX: .5
    Button:
        size_hint:.1,.1
        background_color: 0.1,0.5,0.6,1
        text: "Up"
        pos_hint: {"x":0.8,"y":.8}
        on_press: self.parent.pY+=.1
    Button:
        size_hint:.1,1
        text: "Down"
        pos_hint: {"x":0.8,"top":0.8}
        on_press: self.parent.pY-=.1
    Button:
        size_hint:.1,1
        text: "Left"
        pos_hint: {"x":0.7,"top":0.9}
        on_press: self.parent.pX-= .1
    Button:    
        size_hint:.1,1
        text: "Right"
        pos_hint: {"x":0.9,"top":0.9}
        on_press: self.parent.pX+=.1
    Label:
        size_hint: .1,.1
        text: "I like to moving moving"
        pos_hint: {"x":self.parent.pX,"top":self.parent.pY}
''')
class sahm(App):
    def build(self):
        return kv
if __name__ == '__main__':
    sahm().run()

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...