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()