1.11M Members

tkinter button widget - passing parameter to function

 
0
 

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.

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

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...

 
1
 

Here is an example how to use lambda to pass arguments in Tkinter's button command:

import Tkinter as tk

def getCond(par):
    firstCond = par
    #conditions.remove(firstCond)
    print firstCond
    #print conditions


root = tk.Tk()

firstCond = ''

condNames = ['1', '2', '3', '4',  '5', '6']
for item in condNames:
    # use lambda to pass arguments to command-function
    tk.Button(root, text=str(item), command=lambda i=item: getCond(i)).pack()

root.mainloop()

Also, create your function before you call it.

 
0
 

Hi friends,
i am happy with above code. Can u please explain easily about lambda command plz..

 
1
 

An example might explain it better ...

# normal function declaration
def timestwo1(x):
  return x * 2

# using lambda (not anonymous)
timestwo2 = lambda x: x * 2

# test it ...
print(timestwo1(4))  # 8
print(timestwo2(4))  # 8

# or make it anonymous ('on the fly')
print((lambda x: x * 2)(4))  # 8
 
0
 

Thank u very much sir i got clearly understood from your explanation

 
0
 

Lambda was introduced to Python from Lisp and allows for easier functional programming.

Question Answered as of 1 Year Ago by kavin babu, vegaseat, sneekula and 1 other
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article