类型错误:quit() 需要 1 个位置参数,但给出了 2 个(键盘绑定) [英] TypeError: quit() takes 1 positional argument but 2 were given (keyboard bind)

查看:34
本文介绍了类型错误:quit() 需要 1 个位置参数,但给出了 2 个(键盘绑定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个python代码:

I have this python code:

def initUI(self):
        self.parent.title("Simple menu")
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        #file menu
        fileMenu = Menu(menubar)
        menubar.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(label="Exit", command=self.quit, accelerator="Ctrl+Q")
        self.bind_all("<Control-q>", self.quit)

    def quit(self):
        sys.exit(0)

当我从菜单中选择退出时,它工作正常.但是,当我按 ctrl+q 时,出现此错误:

When I select Exit from the menu, it works fine. However, when I press ctrl+q, I get this error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/__init__.py", line 1538, in __call__
    return self.func(*args)
TypeError: quit() takes 1 positional argument but 2 were given

到底是怎么回事?

推荐答案

当 tk 调用绑定事件函数时,它会传递一个包含所有描述信息的事件 此处.作为简化,当 tk 调用 Button 单击命令函数时,它不传递事件,因为它不需要.已知该事件是 Button-1 单击,并且按钮内的光标位置几乎从不相关.(如果要处理按钮内的其他鼠标事件,或者如果关心鼠标位置,则应显式绑定事件处理程序.)

When tk calls a bound event function, it passes an event with all the information described here. As a simplification, when tk calls Button click command functions, it does not pass an event, because it is not needed. The event is known to be a Button-1 click and the location of the cursor within the button is almost never relevant. (If one wants to handle other mouse events within the button or if one cares about the mouse location, one should explicitly bind an event handler.)

在您的情况下,由于您不关心事件对象,请添加默认为 None 的可选事件参数.当使用 ^Q 而不是按钮调用函数时,这将吞下"事件.

In your case, since you do not care about the event object, add an optional event parameter defaulted to None. This will 'swallow' the event when the function is invoked with ^Q instead of the button.

    def quit(self, event=None):
        sys.exit(0)

这篇关于类型错误:quit() 需要 1 个位置参数,但给出了 2 个(键盘绑定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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