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!
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:
This will pass the global
name
variable to the function as an argument.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 functionFor 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.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.