2016-07-02 176 views
0

我想弄清楚如何绑定一个按钮,使用Kivy语言布局功能。在Python语言中布置按钮时,我已经看到了很多answers。但是一旦一切就绪,你现在通过一个继承自Button的自定义类来引用?绑定按钮用Kivy语言添加按钮后功能

按下时,下面的代码会抛出错误TypeError: show() takes 1 positional argument but 2 were given并导致程序崩溃。

class TimerButton(ButtonBehavior, Image): 
    timer_container = ObjectProperty(None) 
    client_scoreboard = ObjectProperty(None) 

    def __init__(self, **kwargs): 
     super(TimerButton, self).__init__(**kwargs) 
     self.bind(on_press=self.show) 
     self.bind(on_release=self.changeImage) 

    def show(self): 
     print('hi there') 
     self.source = 'assets/mainViewTimerButtonPressed.png' 
     import kivy.animation as Animate 
     anim = Animate.Animation(
      x=self.client_scoreboard.right - self.timer_container.width, 
      y=self.timer_container.y, 
      duration=0.25) 
     anim.start(self.timer_container) 
     self.unbind(on_press=self.show) 
     self.bind(on_press=self.hide) 

    def changeImage(self): 
     self.source = 'assets/mainViewTimerButton.png' 

    def hide(self): 
     import kivy.animation as Animate 
     anim = Animate.Animation(
      x=self.client_scoreboard.width, 
      y=self.timer_container.y, 
      duration=0.25) 
     anim.start(self.timer_container) 
     self.unbind(on_press=self.hide) 
     self.bind(on_press=self.show) 

回答

0

答案是在函数定义中包含类名TimerButton。这是一个我不完全理解的概念,因为函数是在TimerButton类的范围内定义的。但是,嘿,它的作品。

class TimerButton(ButtonBehavior, Image): 
    timer_container = ObjectProperty(None) 
    client_scoreboard = ObjectProperty(None) 

    def __init__(self, **kwargs): 
     super(TimerButton, self).__init__(**kwargs) 
     self.bind(on_press=self.show) 
     self.bind(on_release=self.changeImage) 

    def show(self): 
     print('hi there') 
     self.source = 'assets/mainViewTimerButtonPressed.png' 
     import kivy.animation as Animate 
     anim = Animate.Animation(
      x=self.client_scoreboard.right - self.timer_container.width, 
      y=self.timer_container.y, 
      duration=0.25) 
     anim.start(self.timer_container) 
     self.bind(on_press=self.hide) 

    def changeImage(self): 
     self.source = 'assets/mainViewTimerButton.png' 

    def hide(self): 
     import kivy.animation as Animate 
     anim = Animate.Animation(
      x=self.client_scoreboard.width, 
      y=self.timer_container.y, 
      duration=0.25) 
     anim.start(self.timer_container) 
     self.bind(on_press=self.show) 
0

是叫你.bind()设定的功能,其传递您的函数没有准备参数的kivy代码。自从我上次使用kivy以来已经有一段时间了,所以我不能确定,但​​我认为事件的细节被传递给函数。

因此,您的事件处理程序的定义应该是这样的:

def show(self, event): 
    ... 

def hide(self, event): 
    ... 

如果你好奇,你可以在这些函数内print(event),看看有什么在被送到