467,088 Members | 1,315 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,088 developers. It's quick & easy.

Tkinter and commands

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
  • viewed: 2603
Share:
1 Reply
YarrOfDoom
Expert 1GB
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.

Similar topics

2 posts views Thread by Paul A. Wilson | last post: by
4 posts views Thread by Rama Calaga | last post: by
1 post views Thread by Richard Lewis | last post: by
2 posts views Thread by Stewart Midwinter | last post: by
9 posts views Thread by Tuvas | last post: by
14 posts views Thread by Hendrik van Rooyen | last post: by
5 posts views Thread by half.italian@gmail.com | last post: by
2 posts views Thread by Kevin Walzer | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.