tkinter button widget - passing parameter to function

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Feb 2008
Posts: 1
Reputation: rude_god is an unknown quantity at this point 
Solved Threads: 0
rude_god rude_god is offline Offline
Newbie Poster

tkinter button widget - passing parameter to function

 
0
  #1
Jan 7th, 2009
Hi all

I've been messing about with this bit of code. Basically what it's
supposed to do is create these six buttons, which when clicked pass a parameter to a function and then call that function. The function basically removes one condition from a larger list depending on which button is clicked The problem is that the way I've written it, the functions runs automatically before the user actually clicks the button.

[code = python]
firstCond = ''
condNames = ['1', '2', '3', '4', '5', '6']
for item in condNames:
button = Button(frame, name = str(item), text = str(item), command = getCond(item)).pack()
def getCond(par):
firstCond = par
conditions.remove(firstCond)
print firstCond
print conditions
[/code]

So I want the function to run when the button is clicked, not automatically on its own. Now I know that the reason it does this is because of the brackets following getCond(item). However, I cannot see any other way of passing the parameter to the function.

Obviously, I could make separate functions for each condition, but I'm just wondering if I could do it more elegantly in this way? It would be a pain if I had 100 conditions instead of 6...
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,297
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 178
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: tkinter button widget - passing parameter to function

 
0
  #2
Jan 7th, 2009
Here is an example how to use lambda to pass arguments in Tkinter's button command:
  1. import Tkinter as tk
  2.  
  3. def getCond(par):
  4. firstCond = par
  5. #conditions.remove(firstCond)
  6. print firstCond
  7. #print conditions
  8.  
  9.  
  10. root = tk.Tk()
  11.  
  12. firstCond = ''
  13.  
  14. condNames = ['1', '2', '3', '4', '5', '6']
  15. for item in condNames:
  16. # use lambda to pass arguments to command-function
  17. tk.Button(root, text=str(item), command=lambda i=item: getCond(i)).pack()
  18.  
  19. root.mainloop()
Also, create your function before you call it.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the Python Forum


Views: 1476 | Replies: 1
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC