简体   繁体   中英

Kivy - update numerical property in KV file on_touch_down

I have a python variable val which is updated based on when a location is pressed in the canvas, and I'm having trouble understanding how to update the value in the KV file.

I think I need to use some kind of binding event, but unsure how to go about doing this. Can someone suggest a solution?

Minimal working example (if you touch near the tip of the slider on the left, I want to it to jump to the opposite side)


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

test.kv

#: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

You are not changing val property of MainScreen , You are declaring a local variable named val in your if clause. Simply use self.val instead of 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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