如何在kivy python中将on_press绑定到GridLayout

时间:2018-02-10 08:47:12

标签: python kivy

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

这是我的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()

1 个答案:

答案 0 :(得分:0)

在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',这是指存在的另一种方法。确保您的信件案例匹配。

here

相关问题