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")
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__
TypeError: printInput() missing 1 required positional argument: 'name'
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.