tkinter TypeError: missing 1 required positional a

2020-03-31 04:44发布

I´m new to python and practicing, and I have now written this piece of coding, but I´m getting an error I do not know how to resolve, could someone help me please?

This is my code:

from tkinter import *

root = Tk()

name = 'donut'

def printInput(event, name):
    print("Your name is %s, and you are years old." % (name))

button_1 = Button(root, text="Submit")
button_1.bind("<Button-1>", printInput)
button_1.pack()

root.mainloop()

And when I click on submit, I get this error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\error\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
TypeError: printInput() missing 1 required positional argument: 'name'

What am I doing wrong?

Thanks!

2条回答
来,给爷笑一个
2楼-- · 2020-03-31 05:27

You have the function printInput which has two parameters, but when it is called, tkinter only passes it one argument, i.e. the event.

One way to pass the name argument as well is to use a lambda function:

button_1.bind("<Button-1>", lambda event:printInput(event,name))

This will pass the global name variable to the function as an argument.

查看更多
家丑人穷心不美
3楼-- · 2020-03-31 05:29

tkinter will call your function with only one argument. Your function expects 2 so it breaks. Just refer to the global value name from the function

def printInput(event):
    print("Your name is %s, and you are years old." % (name))

For a small learner program this might be ok but you may wish to find a nicer way to get that value into your function than using a global as you create larger more complex and/or reusable scripts.

One way to do that is to partially apply your function before passing it to the tkinter widget using the library function functools.partial.

from functools import partial
# ...

button_1.bind("<Button-1>", partial(printInput, name=name))

You can create a new function with the name keyword argument preloaded and pass it to the button, this function only expects one argument and it all works ok.

查看更多
登录 后发表回答