CandyGum CandyGum -4 years ago 650
Python Question

tkinter TypeError: missing 1 required positional argument:

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!

Answer Source

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 first argument preloaded and pass it to the button, then it only expects one argument and all works ok. This is a technique called currying, which is from functional programming.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download