首页 > 解决方案 > Kivy v1.9.1 canvas.clear() 未按预期工作

问题描述

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

具有父变量的第一个 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()

标签: pythonkivy

解决方案


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

您的MyPaintWidget类覆盖 on_touch_down 但未能将触摸传递给其子级,因此 Button 永远不会接收到触摸并且永远不会有机会被按下。

添加return super(MyPaintWidget, self).on_touch_down(touch)MyPaintWidget.on_touch_down调用自动为你处理这个的父类方法。


推荐阅读