Passing Arguments in tkinter bindings

Question:

from tkinter import *
from functools import partial
root = Tk()
  
root.geometry( "200x200" )
def show(event,y):
    print(y)
    print(clicked.get())
options = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday"
]
clicked = StringVar()
clicked.set( "Monday" )
y='test'
# Create Dropdown menu
drop = OptionMenu( root , clicked , *options,command=partial(show,y) )
drop.pack()

root.mainloop()

In the above program I have used the partial module to pass the argument to the function ‘show’
why the above program is not printing the value of y as ‘test’ but giving the value of clicked.get()

Asked By: Daniel C John

||

Answers:

It is because the first parameter y is being passed to the argument you’ve (incorrectly) named event. When tkinter calls the command, it automatically adds the value as a parameter. This goes to the second argument which you’ve named y.

You can solve this by renaming event to y since that’s what you’re passing. Then, change y to new_value (or something similar) to accept the argument passed by the option menu.

def show(y, new_value):
    print(f"y: {y}")
    print(f"new_value: {new_value}")
    print(f"clicked.get(): {clicked.get()}")
Answered By: Bryan Oakley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.