Sho*_*dan 2 python widget kivy
我是一名新手程序员,目前正在学习使用kivy作为GUI平台的python.
我正在阅读kivy手册并正在研究小部件.我想在教程画家小部件上尝试一些东西,但经过几个小时的尝试后,未能这样做.
我想要的应该很简单.我有小部件,它在触摸屏幕后创建一个随机行.我认为在某个区域触摸屏幕后重复自动添加线条会很有趣.所以我创建了一个函数,可以使用数据"注入"小部件来创建更多行.
但我根本无法与小部件"沟通".我不知道小部件"实例"名称是什么.所以我通过命名画家来创建实例,让我们共享代码:
import kivy
import time
from random import random
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.graphics import Color, Ellipse, Line
class MyPaintWidget(Widget):
def on_touch_down(self, touch,):
with self.canvas:
Color(random(), random(), random())
touch.ud['Line'] = Line(points=(touch.x, touch.y))
touch.ud['Line'].points += [random()*1000, random()*1000 ]
begin()
def touchme():
touch.ud['Line'].points += [random()*1000, random()*1000 ]
print 'touchme'
class MyPaintApp(App):
def build(self):
painter = MyPaintWidget()
return painter
def begin():
def my_callback(dt):
print 'begin'
painter.touchme()
Clock.schedule_interval(my_callback, 1.)
if __name__ == '__main__':
MyPaintApp().run()
Run Code Online (Sandbox Code Playgroud)
希望soneone可以为我提供如何做到这一点的答案,也许可以向我解释一下小部件是如何工作的.我将它视为python中的标准类,但我认为它的工作方式略有不同.
干杯.
不确定我是否理解你想要实现的目标,但我猜你可以将代码从你的begin方法移到on_touch_down方法中,使后者看起来像这样:
def on_touch_down(self, touch):
with self.canvas:
Color(random(), random(), random())
touch.ud['Line'] = Line(points=(touch.x, touch.y))
touch.ud['Line'].points += [random()*1000, random()*1000 ]
Clock.schedule_interval(self.touchme, 1.)
Run Code Online (Sandbox Code Playgroud)
问题是touchme需要touch对象,所以你必须将它作为参数传递.这样可能有用,但我没有检查:
def on_touch_down(self, touch):
with self.canvas:
Color(random(), random(), random())
touch.ud['Line'] = Line(points=(touch.x, touch.y))
touch.ud['Line'].points += [random()*1000, random()*1000 ]
Clock.schedule_interval(lambda: self.touchme(touch), 1.)
def touchme(self, touch):
touch.ud['Line'].points += [random()*1000, random()*1000 ]
print 'touchme'
Run Code Online (Sandbox Code Playgroud)
一般来说,我建议你尝试对变量范围有更好的感觉.在您的代码中,您尝试访问变量painter以及touch它们不可见的位置.
我自己也只是开始使用kivy,所以也许我可以在几周内给出更完整的答案.;)