如何使 on_touch_down 小部件具体化?

How do I make on_touch_down widget specific?

我正在尝试在 kivy 中创建一个简单的绘图应用程序,但我遇到了一些问题

on_touch_down

功能,因为它涉及整个 class 而不仅仅是特定的小部件。因此,当我使用 on touch down 和 on touch move 函数在 canvas 上绘制时,它会影响并有效地禁用绑定到按钮的 touch down 函数。这是按钮不起作用的代码。

python代码:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.graphics import Line
from kivy.graphics import *
from kivy.uix.widget import Widget
class MyScreenManager(ScreenManager):
    pass

class MenuScreen(Screen):
    pass

class DrawScreen(Screen):
    def on_touch_down(self, touch):
        with self.canvas.before:
            Color(1, 0, 0)
            touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)

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



class DrawApp(App):
    def build(self):
        return MyScreenManager()

DrawApp().run()

kivy代码:

<MenuButton@Button>:
    font_size: 65
    size_hint: 0.4, 0.25

<MyScreenManager>:
    MenuScreen:
        id: menu
        name: "menu"

    DrawScreen:
        id: draw
        name: "draw"

<MenuScreen>:
    canvas.before:
        Color:
            rgba: 1,1,1,1
        Rectangle:
            size: self.size
            pos: self.pos

    MenuButton:
        text: "Draw"
        on_release: root.manager.current = "draw"
        pos_hint:{"center_x":0.5, "center_y":0.6}
    MenuButton:
        text: "Quit"
        on_release: app.stop()
        pos_hint:{"center_x":0.5, "center_y":0.3}

<DrawScreen>:
    canvas.before:
        Color:
            rgba: 1,1,1,1
        Rectangle:
            size: self.size
            pos: self.pos


    Button:
        id: but
        size_hint: 0.2,0.1
        pos_hint_x: 0 + self.width
        font_size: 30
        text: "Back"
        on_release: root.manager.current = "menu"

我设法通过使用 collide_point 找到了一个简单的解决方法,这是我的解决方法代码:

class DrawScreen(Screen):
    def on_touch_down(self, touch):
        but = self.ids.but
        if but.collide_point(touch.x, touch.y):
            self.manager.current = "menu"

        else:
            with self.canvas.before:
                Color(1, 0, 0)
                touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)

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

但是,虽然这行得通,但它带来了一大堆新问题,比如我必须手动配置每个按钮以在按下时更改来源,并且在释放按钮之前功能不会 运行。这也意味着我添加到 class 的所有内容都必须添加到 if 语句中。

我非常肯定必须有更简单的方法。我的第一个想法是,也许有人可以添加触地时只影响一个小部件?我的第二个想法是,如果不在 canvas 或其他东西上画画会更好吗?

感谢任何帮助或指点,谢谢!

当你覆盖一个方法时,你必须return与super相同的方法class

像这样:

...

class DrawScreen(Screen):
    def on_touch_down(self, touch):
        with self.canvas.before:
            Color(1, 0, 0)
            touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)
        return super(DrawScreen, self).on_touch_down(touch)

    def on_touch_move(self, touch):
        touch.ud["line"].points += (touch.x, touch.y)
        return super(DrawScreen, self).on_touch_move(touch)