Keyboard Shortcut “Takes 1 positional argument but 2 were given”

拈花ヽ惹草 提交于 2019-12-18 05:25:10

问题


Trying to make a keyboard shortcut to reset a game. Earlier in the __init__ class I create a menu to start a new game, and use self.reset to reset the score/grid etc. I now have been trying to implement the shortcut with the same command - the reset being a method within the class.

self._master.bind_all('<Control-n>', self.reset)

This is the error:

TypeError: reset() takes 1 positional argument but 2 were given

My confusion is that the self.reset works fine earlier in the __init__ but then does not work for the shortcut?

I do not see how the shortcut is even giving any positional arguments to the method.

Now if I change it to self.reset() I get an error about the current class missing the _game attribute.

Here is the reset method:

def reset(self):
    self._game.get_default_score()
    self._game.reset()
    self._grid_view.draw(self._game.grid, self._game.find_connections())

回答1:


That is easy - whatever the mechanism that binds the shortcut does, it is passing an extra parameter to your reset method.

Since you don't care what it is at all, just declare your method to accept an extra optional parameter, and you should be good:

...
def reset(self, event=None):
    self._game.get_default_score()
    ...

So, searching for "bind_all" we find out your code actually uses tkinter, and what tkinter passe along to your method is the "event" - an object with information on what key whas actually pressed and such - http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm



来源:https://stackoverflow.com/questions/44288364/keyboard-shortcut-takes-1-positional-argument-but-2-were-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!