更新字典时标记文本更改

时间:2017-12-12 20:59:28

标签: 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=Label(root,text=dict['c']).pack()
    Button(command=setit('a',dict,3)).pack()

按下按钮时,我想要更新字典和相应的标签。你会怎么做?优选不含OOP。谢谢!

2 个答案:

答案 0 :(得分:0)

首先,代码示例中存在两个问题:

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

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

2)按钮的command选项将函数作为参数,但您执行command=setit('a',dict,3),因此您可以在创建按钮时执行该函数。要将带参数的函数传递给按钮命令,可以使用lambda

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

然后,要在更改字典中的值时更新标签,您可以将标签存储在具有相同键的字典中,并使用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()

答案 1 :(得分:-1)

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

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!")

有关标签的更多信息,请参阅here

注意:dict是python中的保留字,因此最好不要将其用作变量的名称。同样适用于strint

相关问题