如何绑定到类中的函数并且仍然使用事件变量? [英] How do I bind to a function inside a class and still use the event variable?

查看:49
本文介绍了如何绑定到类中的函数并且仍然使用事件变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

bind函数将self设置为事件变量,并忽略/引发事件错误。即使我使用args *,也无法找到将事件参数传递给正确的变量并为该函数保持自我的方法。我可以做一个,但不能两个都做。

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.

推荐答案

问题是您正在尝试使用实例方法

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)

其中 box 是某事物的实例,但是 Player 不是。

相反:

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)

创建播放器类的实例,然后绑定到instances方法,而不是类方法。

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

这篇关于如何绑定到类中的函数并且仍然使用事件变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆