【问题标题】:How to Bind on_press to GridLayout in kivy python如何在 kivy python 中将 on_press 绑定到 GridLayout
【发布时间】:2018-02-10 08:47:12
【问题描述】:

我试图用 kv 语言将 on_press 方法绑定到 gridLayout,但我得到了这个错误 AttributeError:pressed。我什至在 kivy 文档中也做了一些研究,但没有任何帮助。所以如果有人能解决这个问题,请你可能是一个很好的资源

这是我的 testApp.py

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

class screendb(BoxLayout):
      def mycall_back(self):
          print('hello')

class testApp(App):
    def build(self):
        return screendb()

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

这是我的 testApp.kv

<Screendb@BoxLayout>:
        GridLayout:
             on_pressed:root.Mycall_back()

【问题讨论】:

  • 欢迎来到Stack Overflow en español罗纳德。您不应发布代码或错误消息的图像,而是直接将实际代码或消息复制并粘贴到帖子中。见How do I format my code blocks?。另一方面,GridLayout 没有定义 on_release 事件,例如 Button。
  • 感谢 FJSevilla 的回复
  • 我已经编辑了我的问题
  • 无论如何我可以将 on_release 添加到 GridLayout 或任何布局中

标签: python kivy


【解决方案1】:

在你的 py 文件中:

# Behaviors let you add behavior from one widget to another widget
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.gridlayout import GridLayout

# We create a new widget that is a GridLayout with access to Button Behaviors
# Like Button's 'on_press' method
class ButtonGrid(ButtonBehavior, GridLayout):
    pass

class screendb(BoxLayout):
      def mycall_back(self):
          print('hello')

class testApp(App):
    def build(self):
        return screendb()

在您的 kv 文件中:

# We create a Root Widget for the ButtonGrid
<ButtonGrid>:

<Screendb@BoxLayout>:
    # We add an instance of the ButtonGrid class to our main layout
    ButtonGrid:
        # We can now use on_press because it is a part of the ButtonBehavior class, that makes up your ButtonGrid class.
        on_press:root.mycall_back()

注意:您的帖子中也有一些小错误。例如,没有方法'on_pressed',只有'on_press',您还在py文件中将回调写为'mycall_back',而在kv文件中将其写为'Mycall_back',它指的是存在的不同方法。确保您的字母大小写匹配。

video example

【讨论】:

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