【问题标题】:Kivy on_press vs on_touch_downKivy on_press 与 on_touch_down
【发布时间】:2018-10-24 17:48:17
【问题描述】:

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

我将 on_touch_down 更改为 on_press,两个按钮和谐地存在/运行。

谁能告诉我为什么?

这是一个示例 .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在哪里?
  • 它们代替了 .kv 文件中的 on_press 事件。

标签: python python-3.x kivy kivy-language


【解决方案1】:

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

如果您的按钮正在执行其他操作,并且不会相互抵消,那么您会看到这两个操作都触发了。例如,如果一个按钮打印“hello”,一个打印“world”,那么按下似乎不起作用的按钮将打印“hello world”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多