0

I'm new to coding and i've been messing around with tkinter.

My labels have text, that is supposed to change when the dictionary values are updated.

An example of my code:

    def setit(point, adic,number):
         adic[point] = adic[point]+number

    dict={'a':4,'b':8,'c':3}
    aa=Label(root,text=dict['a']).pack()
    bb=Label(root,text=dict['b']).pack()
    cc=Label(root,text=dict['c']).pack()
    Button(command=setit('a',dict,3)).pack()

When the button is pressed i want both the dictionary and the appropriate Label to update. How would you do that? Preferably without OOP. Thanks!

2 Answers2

0

First of all, there are two problems in your code sample:

1) .pack() returns None, so when you do aa=Label(root,text=dict['a']).pack(), you store None in the variable aa, not the label. You should do:

aa = Label(root,text=dict['a'])
aa.pack()

2) The command option of a button takes a function as argument but you do command=setit('a',dict,3) so you execute the function at the button creation. To pass a function with arguments to a button command, you can use a lambda:

Button(command=lambda: setit('a',dict,3))

Then, to update the label when the value in the dictionary is changed, you can store your labels in a dictionary with the same keys and change the text of the appropriate label with label.configure(text='new value'):

import tkinter as tk

def setit(point, adic, label_dic, number):
     adic[point] = adic[point] + number  # change the value in the dictionary
     label_dic[point].configure(text=adic[point])  # update the label

root = tk.Tk()

dic = {'a': 4, 'b': 8, 'c': 3}
# make a dictionary of labels with keys matching the ones of dic
labels = {key: tk.Label(root, text=dic[key]) for key in dic}
# display the labels
for label in labels.values():
    label.pack()

tk.Button(command=lambda: setit('a', dic, labels, 3)).pack()

root.mainloop()
j_4321
  • 15,431
  • 3
  • 34
  • 61
-1

You can use a StringVar instead of specifying the text value. That looks like:

d={'a':StringVar(),'b':StringVar(),'c':StringVar()}
aa=Label(root,textvariable=d['a'])
bb=Label(root,textvariable=d['b'])
cc=Label(root,textvariable=d['c'])

aa.pack()
bb.pack()
cc.pack()

And then whenever you want to change the label, you can do

d['a'].set("new text!")

See here for more info on labels.

Note: dict is a reserved word in python, so it's best to not use that as the name of your variable. Same goes for str, int, etc.

RagingRoosevelt
  • 2,046
  • 19
  • 34