简体   繁体   English

Kivy on_press与on_touch_down

[英]Kivy on_press vs on_touch_down

I have a number in a Kivy label and 2 buttons, one which increments that number, one which decrements it. 我在Kivy标签中有一个数字和2个按钮,一个按钮增加该数字,一个按钮减少该数字。 I was surprised to find that when using on_touch_down the + button would not work. 我很惊讶地发现使用on_touch_down时+按钮不起作用。 I commented out the - button and the + button started working. 我注释掉了-按钮,而+按钮开始起作用。

I changed the on_touch_down to on_press and both buttons exist/function harmoniously. 我将on_touch_down更改为on_press,并且两个按钮均和谐存在/功能。

Can someone tell me why? 有人可以告诉我为什么吗?

Here is an example .py file: 这是一个示例.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()

and the .kv file: 和.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 fires everything within a widget tree. on_touch_down会触发小部件树中的所有内容。 Your buttons were cancelling each other out. 您的按钮相互抵消。

If your buttons were doing something else, something that did not cancel each other out, then you would see both actions fire. 如果您的按钮正在执行其他操作,而这些操作并未彼此抵消,那么您将看到两个动作均触发。 Such as if one button printed "hello" and one printed "world" then pressing the button that didn't appear to be working would print "hello world". 例如,如果一个按钮打印“ hello”,而一个按钮打印“ world”,然后按一下似乎无效的按钮,则会打印“ hello world”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM