BoobaGump
BoobaGump

Reputation: 535

Bind a tkinter widget to a function containing args - Use of Lambda

There is a list :

liste_physical_activity.insert(1, pa1)
liste_physical_activity.insert(2, pa2)
liste_physical_activity.bind('<<ListboxSelect>>',  CurSelet_physical_activity)
liste_physical_activity.pack()

Linked to the following function :

def CurSelet_physical_activity(event, window_mother):
     # stuff

Even with using lambda it doesn't work:

<<ListboxSelect>>', lambda event, 
window_mother=main_window  CurSelet_physical_activity (event, window_mother))

The problem is that the main_window has been created in another file.py, so he doesn't know it.

How can i fix this ?

EDIT for the ref problem :

main.py

from Energy_Requirement import*
main_window =Tk()
bouton_energy_requirement= Button(main_window, text="Estimation of energy requirement", command=lambda:energy_requirement(main_window))
bouton_energy_requirement.pack()

file1.py

def energy_requirement(window_mother):
    pa1="NRC"
    pa2="Kornfeld"     
    window5=Toplevel(window_mother)
    liste_physical_activity = Listbox(window5,width=80, height=5)
    liste_physical_activity.insert(1, pa1)
    liste_physical_activity.insert(2, pa2)
    liste_physical_activity.bind('<<ListboxSelect>>',  CurSelet_physical_activity)
    liste_physical_activity.pack()

def CurSelet_physical_activity(event):
    global liste_physical_activity
    value=str(liste_physical_activity.get(liste_physical_activity.curselection()))

    if value==pa1:
       ER=1
       label = Label(main_window, text="Energy Requirement (kcal ME/day)")
       label.pack()
       show_ER=StringVar()
       show_ER.set(ER)
       entree_ER = Entry(main_window,textvariable=show_ER,width=30)
       entree_ER.pack()


    if value==pa2:
       ER=2
       label = Label(main_window, text=" Energy Requirement (kcal ME/day)")
       label.pack()
       show_ER=StringVar()
       show_ER.set(ER)
       entree_ER = Entry(main_window,textvariable=show_ER,width=30)
       entree_ER.pack()

Upvotes: 0

Views: 768

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385980

energy_requirement is being passed a reference to main_window, so all you need to do is pass that value along in the binding. This should work:

def energy_requirement(window_mother):
    ...
    liste_physical_activity.bind('<<ListboxSelect>>',  
        lambda event, mw=window_mother: CurSelet_physical_activity(event, mw))

You'll then need to modify CurSelet_physical_activity to accept this additional parameter:

def CurSelet_physical_activity(event, main_window):
    ...

    if value==pa1:
       ER=1
       label = Label(main_window, text="Energy Requirement (kcal ME/day)")
       ...

It doesn't look like you use event anywhere in CurSelet_physical_activity, so you can remove that from the binding and from the parameter list of the function if you want.

Upvotes: 1

Related Questions