如何使on_touch_down小部件具体化?

时间:2017-12-05 21:21:59

标签: python kivy kivy-language

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

on_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)

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

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

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

1 个答案:

答案 0 :(得分:1)

当你覆盖一个方法时,你必须返回超类的相同方法

类似的东西:

...

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)