Connecting Tech Pros Worldwide Forums | Help | Site Map

Tkinter and commands

Newbie
 
Join Date: Mar 2008
Posts: 10
#1: May 29 '09
With a right click, a popup menu will appear, allowing to select from a list of colours. The queston is: is it necessary to create a callback function for each colour? How may I pass on information to the callback function?

Here's a short example script:

Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2.  
  3. root = Tk()
  4.  
  5. def colour():
  6.     print 'Which colour was it?' 
  7. # Here, the actual colour should've been printed instead!
  8.  
  9. # create a popup menu
  10. menu = Menu(root, tearoff=0)
  11. menu.add_command(label='Green', command=colour)
  12. menu.add_command(label='Blue', command=colour)
  13.  
  14. # create a canvas
  15. frame = Frame(root, width=128, height=128)
  16. frame.pack()
  17.  
  18. def popup(event):
  19.     menu.post(event.x_root, event.y_root)
  20.  
  21. frame.bind("<Button-3>", popup)
  22. mainloop()
  23.  

YarrOfDoom's Avatar
Expert
 
Join Date: Aug 2007
Location: Belgium
Posts: 1,120
#2: May 29 '09

re: Tkinter and commands


This can be achieved by using lambda
Expand|Select|Wrap|Line Numbers
  1. command = lambda:colour("Blue")
However, when using this with 'bind', don't forget to make the lambda form accept the 'event'-argument so it can pass it on to your callback:
Expand|Select|Wrap|Line Numbers
  1. widget.bind("<sequence>", lambda ev: callback_function(ev, arg))
More info on lambda can be found here.
Reply