python - 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()
解决方案
触摸从小部件树向下分派,它们进入根小部件,该小部件必须将触摸向下传递给其子级(或者如果需要,则不这样做)。
您的MyPaintWidget
类覆盖 on_touch_down 但未能将触摸传递给其子级,因此 Button 永远不会接收到触摸并且永远不会有机会被按下。
添加return super(MyPaintWidget, self).on_touch_down(touch)
到MyPaintWidget.on_touch_down
调用自动为你处理这个的父类方法。
推荐阅读
- java - org.apache.kafka.common.errors.TimeoutException:获取主题元数据时超时
- apache-kafka - SerializationException:反序列化 Avro 消息时出错
- c# - NetCore 2.2 中的版本控制
- ruby-on-rails - How to decrypt signed cookies
- file - 为什么我的缓存在 Laravel 4.2 上使用 0 分钟时不会过期
- c# - 在 Visual Studio 代码分析器 (Roslyn) 中确定目标框架
- angular - 如何在 Jhipster (spring boot + angular) 应用程序上设置上下文路径
- python - 尝试在 Windows 上安装烧瓶时出现问题(错误:命令错误退出状态为 1)
- javascript - 使用 javascript 将字节转换为 PDF
- javascript - 如何在类内部构造类的使用结构以避免循环引用?