我有一个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
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
答案 0 :(得分:1)
您没有更改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