How do I bind to a function inside a class and sti

2019-08-24 17:59发布

class Player():
    def __init__():
        ...
    def moveHandle(self, event):
        self.anything = ...
box.bind("<Key>", Player.moveHandle)

The bind function sets self as the event variable and ignores/throws up an error for event. I can't find a way to pass the event argument to the correct variable and maintain self for that function, even if I use args*. I can do one or the other, but not both.

I'm probably just lacking some basic knowledge about classes to be honest, I taught them to myself and didn't do it very thoroughly.

If I made a syntax mistake, it's because of me rewriting out the code incorrectly; in my program, the code works until the variables get passed.

1条回答
聊天终结者
2楼-- · 2019-08-24 18:38

the problem is that you are trying to use an instance method as a class method.

consider the following:
class Player():
    def __init__():
        ...
    def moveHandle(self, event):
        self.anything = ...
box.bind("<Key>", Player.moveHandle)

where box is an instance of something, but Player is not.
instead this:

class Player():
    def __init__(self):
        ...
    def moveHandle(self, event):
        self.anything = ...
p = Player()
box.bind("<Key>", p.moveHandle)

creates an instance of the player class, and then binds to the instances method, not the class method.

查看更多
登录 后发表回答