AlMa
AlMa

Reputation: 269

Tkinter: Text widgets callback refering to wrong widget

I have a Tkinter window containing some Text widgets. These widgets:

  1. Are created from a list of StringVar (1 widget per list element, variable number based on the list length).
  2. Display the text of the corresponding StringVar.
  3. Have their background colour defined by the text of the corresponding StringVar.
  4. Call a function analyse_display_callback_colour when the "Return" key from the keyboard is pressed.

Problem:

The analyse_display_callback_colour always receive the index of the last created widget. It means that instead of having a reference to the modified Text widget, if always has a reference to the last created widget.

Could someone explain me how to trigger the function analyse_display_callback_colour for the widget in which the "Return" key is pressed?

MWE

from tkinter import StringVar, Text, END, Tk

def analyse_display_callback_colour(event,widgets,index):
    print(widgets[index])

############### MAIN CODE ###############

window_main = Tk()

colours = [StringVar(window_main,"deep sky blue"),StringVar(window_main,"forest green"),StringVar(window_main,"red")]
colours_widgets = []

for n in range(0,len(colours)):
    colours_widgets.append(Text(window_main, width=15, height=1, bg=colours[n].get()))
    colours_widgets[n].insert(END,colours[n].get())
    colours_widgets[n].bind('<Return>', lambda e:analyse_display_callback_colour(event=e,widgets=colours_widgets,index=n))
    colours_widgets[n].grid(column=0,row=n)

window_main.mainloop()

Upvotes: 1

Views: 31

Answers (0)

Related Questions