By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,965 Members | 1,631 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,965 IT Pros & Developers. It's quick & easy.

Tkinter and commands

P: 16
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.  
May 29 '09 #1
Share this Question
Share on Google+
1 Reply


YarrOfDoom
Expert 100+
P: 1,247
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.
May 29 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.