Python Tinter dropdown menu command with click event

Question:

I have a TKinter dropdown menu created with this code:

#menu
menu = Menu(window)
window.config(menu = menu)
subMenu = Menu(menu)

menu.add_cascade(label = "Kies een ander station", menu = subMenu)
subMenu.add_command(label = "Amersfoort", command = print('test'))
subMenu.add_separator()
subMenu.add_command(label = "Amsterdam Centraal", command = print('test2'))
subMenu.add_separator()
#etc..

When I compile and run, the code in the command attribute of each subMenu.add_command() function is being executed right away. I want to achieve this when I click on a menu item. How do I do that?

Asked By: erol_smsr

||

Answers:

Put them in lambdas. This will make the expressions into callables which will patiently wait for the event to occur before executing.

subMenu.add_command(label = "Amersfoort", command = lambda: print('test'))
subMenu.add_separator()
subMenu.add_command(label = "Amsterdam Centraal", command = lambda: print('test2'))
Answered By: Kevin
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.