簡體   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