我正在试图弄清楚如何将使用Kivy语言布局的按钮绑定到一个函数。在使用Python语言布置按钮时,我看到了很多answers。但是,一旦所有内容到位并且您现在通过继承自Button
的自定义类引用该怎么办?
按下时,下面的代码会抛出错误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 :(得分: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)
答案 1 :(得分:0)
调用你在.bind()
中设置的函数的kivy代码正在传递一个你的函数没有准备好的参数。自从我上次使用kivy以来已经有一段时间了,所以我无法确定,但我认为事件详细信息会传递给函数。
因此,您对事件处理程序的定义应如下所示:
def show(self, event):
...
def hide(self, event):
...
如果您感到好奇,可以在这些功能中print(event)
查看正在发送的内容。