【问题标题】:Label text changing when dictionary is updated更新字典时更改标签文本
【发布时间】:2017-12-12 20:59:27
【问题描述】:

我是编码新手,我一直在玩 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。谢谢!

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以使用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 等也是如此。

      【讨论】:

      • 在本例中,aabbcc 都将是 None
      • @BryanOakley,说得好。我只是漫不经心地复制了 OP 的那部分代码,因为它与他关于更改标签值的问题没有直接关系。
      • 我也会看到,Why would we use a variable class?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多