change label text in widgets created in loop dynamically from a dictionary

Viewed 39

Im working on a tkinter GUI that creates labels from a dictionary. on of the labels is a "Fails" counter (theres another function that updates this value in the dictionary) id like if so when the "fails" is updated in the dictionary, it updates the fails value in the label.

heres a snippet if createing the labels from the dictionary. i cant figure out how to make it so the fails_label text is changed when the dictionary is updated

Thank you

        row = 2
        widgets = {}
        for key in obj2create:

            strEngNumber = obj2create[key][0]
            strLayer = obj2create[key][1]
            strFile = obj2create[key][2]
            intFails = obj2create[key][3] 

            
            strJobKey = key

            job_label = tk.Label(self.frame, text=key, anchor="w",
                                  justify="center", wraplength=701,background=bg)
            job_label.grid(row=row, column=0, pady=10, padx=10, ipady=3)

            eng_label = tk.Label(self.frame, text=strEngNumber, anchor="w",
                                  justify="center", wraplength=701,background=bg)
            eng_label.grid(row=row, column=1, pady=10, padx=10, sticky="w")
            
            layer_label = tk.Label(self.frame, text=strLayer, anchor="w",
                                  justify="center", wraplength=701,background=bg)
            layer_label.grid(row=row, column=2, pady=10, padx=10, sticky="w")
            
            file_label = tk.Label(self.frame, text=strFile, anchor="w",
                                  justify="center", wraplength=701,background=bg)
            file_label.grid(row=row, column=3, pady=10, padx=10, sticky="w")

            fails_label = tk.Label(self.frame, text=intFails, anchor="w",
                                  justify="center", wraplength=701,background=bg)
            fails_label.grid(row=row, column=4, pady=10, padx=10, sticky="w")




1 Answers

You can use trace_add() method like in the example below:

from tkinter import *

def update(var, index, mode):
    label.configure(text=intFails.get())

def functionOnClick():
    intFails.set(intFails.get() + 1)

w = Tk()
w.geometry('400x400')

intFails = IntVar(w, 0)
intFails.trace_add('write', update)

label = Label(w, textvariable=intFails, anchor="w", justify="center", font=('Arial', 22))
label.place(x=0, y=0)

btn = Button(w, text='Click', command=functionOnClick, font=('Arial', 22))
btn.place(x=0, y=80, width = 100, height = 80)

w.mainloop()

This method helps you to automatically detect, when variable was changed. Though it works only with special IntVar() and StringVar(), but I think it's only possible way to do this at least with this type of vars.

On the other hand, you can try to create a class with dictionary as your field and works with it by set property. This link may be useful for you.

Related