Kivy v1.9.1 canvas.clear()无法正常工作

时间:2018-12-06 17:52:04

标签: python kivy

我不太确定为什么画布不能清除。

第一个具有父变量的build(self)实现是可行的。我唯一不同的是,第二种实现是将Button小部件添加到MyPaintWidget,而不是将这两个小部件都添加到默认Widget类中。

对kivy来说是新手,我对python半熟。我很想解释。

from random import random
import kivy
kivy.require('1.9.1')
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import Color, Ellipse, Line

'''
class LoginScreen(GridLayout):
    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.cols=2
        self.add_widget(Label(text='User Name'))
        self.username=TextInput(multiline=False)a
        self.add_widget(self.username)
        self.add_widget(Label(text='password'))
        self.password=TextInput(password=True, multiline=False)
        self.add_widget(self.password)

class MainApp(App):
    def build(self):
            return LoginScreen()

'''
class MyPaintWidget(Widget):

    def on_touch_down(self, touch):
        color = (random(), 1, 1)
        with self.canvas:
            Color(*color)
            d = 30.
            Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d))
            touch.ud['line'] = Line(points=(touch.x, touch.y))
        print(touch)

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]

class MyPaintApp(App):

#WHY ARE THESE TWO IMPLEMENTATIONS OF BUILD SO DIFFERENT?????
    '''
    def build(self):
        parent = Widget()
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear')
        clearbtn.bind(on_release=self.clear_canvas)
        parent.add_widget(self.painter)
        parent.add_widget(clearbtn)
        return parent
    '''
    def build(self):
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear')
        clearbtn.bind(on_release=self.clear_canvas)
        self.painter.add_widget(clearbtn)
        return self.painter

    def clear_canvas(self, obj):
        self.painter.canvas.clear()

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

1 个答案:

答案 0 :(得分:0)

触摸是在窗口小部件树中分派的,它们在根窗口小部件中输入,该根窗口小部件必须将触摸向下传递给其子级(或者如果需要,则不这样做)。

您的MyPaintWidget类会覆盖on_touch_down,但无法将触摸传递给子级,因此Button永远不会收到触摸,也永远不会有被按下的机会。

return super(MyPaintWidget, self).on_touch_down(touch)中添加MyPaintWidget.on_touch_down,以调用自动为您处理此问题的父类方法。