Python 更新词典时标签文本发生变化

Python 更新词典时标签文本发生变化,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我对编码还不熟悉,我一直在和tkinter乱搞 我的标签有文本,应该在更新字典值时更改 我的代码示例如下: 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=

我对编码还不熟悉,我一直在和tkinter乱搞

我的标签有文本,应该在更新字典值时更改

我的代码示例如下:

    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()
按下按钮后,我希望词典和相应的标签都能更新。你会怎么做?最好没有OOP。谢谢

您可以使用而不是指定文本值。这看起来像:

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()
然后,每当你想更改标签时,你都可以这样做

d['a'].set("new text!")
有关标签的更多信息,请参阅


注意:
dict
在python中是一个保留字,因此最好不要将其用作变量名。
str
int
等也是如此。

首先,您的代码示例中有两个问题:

1)
.pack()
返回
None
,因此当执行
aa=Label(root,text=dict['a']).pack()
时,将
None
存储在变量
aa
中,而不是存储在标签中。你应该做:

aa = Label(root,text=dict['a'])
aa.pack()
2) 按钮的
命令
选项将函数作为参数,但您必须执行
command=setit('a',dict,3)
,因此您可以在创建按钮时执行函数。要将带有参数的函数传递给按钮命令,可以使用
lambda

Button(command=lambda: setit('a',dict,3))
然后,要在更改字典中的值时更新标签,可以使用相同的键将标签存储在字典中,并使用
label.configure(text='new value')
更改相应标签的文本:


在本例中,
aa
bb
cc
都将是
None
@BryanOakley,这一点很好。我只是无意识地复制了OP的那部分代码,因为它与他关于更改标签值的问题没有直接关系。
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()