类型错误:printName1() 采用 0 个位置参数,但给出了 1 个 [英] TypeError: printName1() takes 0 positional arguments but 1 was given

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

问题描述

所以我写了一个非常简单的东西,它让我试图弄清楚为什么它不起作用.当您单击时,它会打印一条语句.

So I have this very simple thing I wrote and it's killing me trying to figure out why it won't work. All it does it print a statement when you click.

因此,对于第一个示例,我有一个按钮并直接将函数 printName1 分配给它,效果很好.

So for the first example I had a button and assigned the function printName1 directly to it, which worked perfectly fine.

接下来是使用 .bind() 函数绑定它.因此,在这种情况下,我们只有一个框架,可以根据您按下的按钮打印出某些内容.但不幸的是,每当我使用绑定时,它都会抛出上面显示的错误.引用 tkinter\__init__.py 以解决错误,所以它不是直接在我的代码中的东西,但也许需要以不同的方式完成?谢谢各位.

Then the next thing was to bind it using the .bind() function. So in this case we just have a frame that prints out certain things based on which button you press. But unfortunately whenever I use bind, it throws the error show above. References tkinter\__init__.py for the error, so it's not something directly in my code but maybe it needs to be done differently? Thanks guys.

from tkinter import *

root = Tk()

def printName1():
    print('Jack')

def printName2():
    print('John')

def printName3():
    print('Jill')

frame = Frame(root, width=300, height=250)
frame.bind("<Button-1>", printName1)
frame.bind("<Button-2>", printName2)
frame.bind("<Button-3>", printName3)
frame.pack()

root.mainloop()

该错误令人困惑,因为它看起来应该是 0 时有一个额外的参数.但实际上我需要向函数添加一个参数,这就是事件.所以它应该是 def printName1(event) 等等.只是想我会让你们知道什么对我有用,以防有人偶然发现这个.

The error is confusing because it made it seem like there was an extra argument when there should be 0. But actually I needed to add an argument to the functions and that was event. so it should be def printName1(event) and so on. Just figured I would let you guys know what worked for me in case anyone stumbles upon this.

推荐答案

如果您参考 有关 tkinter 事件和绑定的文档,您将看到当触发事件时,关联的事件对象将作为第一个(也是唯一的)参数传递给有界函数(即 printName1 和你的朋友).

If you refer to the documentation regarding tkinter events and bindings, you will see that when an event is triggered, the associated event object will be passed as the first (and only) argument to the bounded function (being printName1 and friends in your case).

所以你需要做的是修改那些 printName* 函数以接受事件参数.

So what you need to do is to modify those printName* functions to accept the event argument.

def printName1(event):
    print('Jack')

那么您想要实现的目标应该会奏效.

Then what you desired to achieve should work.

当然,您可以按照@TigerhawkT3 的建议将 event 参数设为可选.

Naturally, you could make the event argument optional as @TigerhawkT3 suggested.

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

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