【问题标题】:Dynamically update label text in kivy program (Python)在kivy程序(Python)中动态更新标签文本
【发布时间】:2017-01-25 23:39:19
【问题描述】:

kivy 库的新手,在动态更新属性时遇到了一些麻烦。这里的标签只是一个占位符。最终,我希望显示的图像根据用户点击/触摸的象限顺序变化。

程序运行良好,没有错误,悬停标签(label2)不更新(label1 确实更新)。当我单击四个象限时,象限编号会按我的预期显示在控制台上。每当用户点击 Q1 时,我也会打印出 self.incr,这也会显示并增加,这意味着 incr 属性正在增加。

所以,我不知道为什么它不更新标签。

main.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.image import Image

class TouchInput(Widget):

    def __init__(self,**kwargs):
        self.incr = 5
        super(TouchInput,self).__init__(**kwargs)

    def on_touch_up(self, touch):

        if touch.x < self.width / 2:
            lateral = 'left'
        elif touch.x > self.width / 2:
            lateral = 'right'
        else:
            lateral = None

        if touch.y < self.height / 2:
            vertical = 'bottom'
        elif touch.y > self.height / 2:
            vertical = 'top'
        else:
            vertical = None

        if vertical and lateral:
            if lateral == 'left' and vertical == 'top':
                quadrant = 1
                print 'Q1'
                self.incr += 1
                print self.incr
            elif lateral == 'right' and vertical == 'top':
                quadrant = 2
                print 'Q2'
            elif lateral == 'left' and vertical == 'bottom':
                quadrant = 3
                print 'Q3'
            elif lateral == 'right' and vertical == 'bottom':
                quadrant = 4
                print 'Q4'

class PPVT(App):

    def build(self):
        t = TouchInput()
        print t.incr
        return t


if __name__ == "__main__":
    PPVT().run()

main.kv

<TouchInput>:
    Image:
        source: 'img1.jpg'
        size: root.width, root.height
    Label:
        id: label1
        text: str(root.width)
        pos: root.width / 2, root.height / 2
    Label:
        id: label2
        text: str(root.incr)

【问题讨论】:

    标签: python dynamic kivy


    【解决方案1】:

    使用数字属性,因此 kivy 可以跟踪其变化。

    from kivy.properties import NumericProperty
    ...
    class TouchInput(Widget):
    
        incr = NumericProperty(5)
        ...
    

    【讨论】:

    • 谢谢,效果很好。我很好奇为什么我不能用 self.attr 设置属性并让 kivy 在它确实跟踪 self.width 之类的东西时跟踪它?
    • @Daniel self.width 是一个属性,也可能是一个数字属性。
    猜你喜欢
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2014-03-04
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多