绝望 on_press vs on_touch_down

Kivy on_press vs on_touch_down

我在 Kivy 标签和 2 个按钮中有一个数字,一个用于增加该数字,一个用于减少它。我很惊讶地发现在使用 on_touch_down 时 + 按钮不起作用。我注释掉了 - 按钮和 + 按钮开始工作。

我将 on_touch_down 更改为 on_press 并且两个按钮 exist/function 协调一致。

谁能告诉我为什么?

这是一个示例 .py 文件:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout


class Counter(BoxLayout):

    def count_up(self):
        value = self.ids.the_number.text
        self.ids.the_number.text = str(int(value) + 1)

    def count_down(self):
        value = self.ids.the_number.text
        self.ids.the_number.text = str(int(value) - 1)


class ProofApp(App):
    def build(self):
        return Counter()


if __name__ == '__main__':
    ProofApp().run()

和 .kv 文件:

<Counter>:
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'top'

        BoxLayout:
            orientation: 'horizontal'

            BoxLayout:

                Label:
                    id: the_number
                    text: "1"

            BoxLayout:
                orientation: 'vertical'
                padding: 2

                Button:
                    id: count_up
                    text: "+"
                    on_press: root.count_up()

                Button:
                    id: count_down
                    text: "-"
                    on_press: root.count_down()

on_touch_down 触发小部件树中的所有内容。您的按钮相互抵消了。

如果你的按钮在做其他事情,一些没有相互抵消的事情,那么你会看到两个动作都会触发。例如,如果一个按钮打印 "hello",一个按钮打印 "world",那么按下似乎不起作用的按钮将打印 "hello world".