繁体   English   中英

Kivy-更新KV文件中的数值属性on_touch_down

[英]Kivy - update numerical property in KV file on_touch_down

我有一个python变量val ,它会根据在画布中按下某个位置的时间进行更新,并且在理解如何更新KV文件中的值时遇到了麻烦。

我想我需要使用某种绑定事件,但是不确定如何执行此操作。 有人可以提出解决方案吗?

最小的工作示例(如果您触摸左侧滑块的尖端附近,我希望它跳到另一侧)


main.py

import kivy
from kivy.config import Config
kivy.require('1.9.1')
Config.set('graphics', 'resizable', 1)
Config.set('graphics', 'width', '400')
Config.set('graphics', 'height', '400')

from kivy.app import App
from test import TestWidget

class TestApp(App):

    def build(self):
        return TestWidget()   

if __name__ == '__main__':
    TestApp().run()

test.py

from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import NumericProperty

class TestWidget(RelativeLayout):

    def __init__(self, **kwargs):
        super(TestWidget, self).__init__(**kwargs)

        Builder.load_file('test.kv')

        sm = ScreenManager()
        sm.add_widget(MainScreen(name='MainScreen'))
        self.add_widget(sm)

class MainScreen(Screen):
    lineX = 395 / 2
    lineY = 405 / 2
    circleRad = 400 / 2
    val = NumericProperty(2500)

    def on_touch_down(self, touch):
        # left
        if 50 <= touch.x <= 75 and 195 <= touch.y <= 210:
            val = 2500
            print val

        # right
        elif 320 <= touch.x <= 350 and 200 <= touch.y <= 215:
            val = 7500
            print val

测试文件

#:import math math

<MainScreen>:
    FloatLayout:
        canvas:
            Line:
                points: [root.lineX, root.lineY, root.lineX +.75 *(root.circleRad *math.sin((math.pi /5000 *(root.val)) +math.pi)), root.lineY +.75 *(root.circleRad *math.cos((math.pi /5000 *(root.val)) +math.pi))]
                width: 2

您没有更改MainScreen val属性,而是在if子句中声明了一个名为val的局部变量。 只需使用self.val而不是val

    if 50 <= touch.x <= 75 and 195 <= touch.y <= 210:
        self.val = 2500
        print self.val

    # right
    elif 320 <= touch.x <= 350 and 200 <= touch.y <= 215:
        self.val = 7500
        print self.val

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM