我该如何使on-hung-down控件特定?

2024-09-28 17:02:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在kivy中创建一个简单的绘图应用程序,但我有一些问题

on_touch_down

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

python代码:

^{pr2}$

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\u 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语句中。

我很肯定一定有更简单的方法。我的第一个想法是,也许可以添加on touch down来只影响一个widget?我的第二个想法是,也许最好不要在画布上画画什么的?

任何帮助或建议,谢谢!


Tags: 代码posselfidsizeon按钮but
1条回答
网友
1楼 · 发布于 2024-09-28 17:02:21

重写方法时,必须返回与超级类相同的方法

像这样:

...

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)

相关问题 更多 >