Tkinter:整数作为标签覆盖

时间:2016-01-19 17:04:47

标签: python tkinter labels

我在for循环中创建标签,每次在我的应用程序上触发事件(鼠标单击)时都会显示整数。问题是,旧标签不会被删除,而新标签会在它们之上出现,造成大混乱。 以下是您可以尝试的工作代码:

import numpy as np
import Tkinter as tk

class Plot(object):

    def __init__(self, win):
        self.win = win

        self.bu1 = tk.Button(win,text='Load',command=self.populate,fg='red').grid(row=0,column=0)

        self.listbox = tk.Listbox(win, height=5, width=5)
        self.listbox.grid(row=1,column=0)#, rowspan=10, columnspan=2)
        self.listbox.bind("<Button-1>", self.print_area)

    def populate(self):
        """Populate listbox and labels"""

        self.time = [1,2,3]
        self.samples = ['a','b','c']
        for item in self.time:
            self.listbox.insert(tk.END,item)

        for i,v in enumerate(self.samples):
            tk.Label(self.win, text=v).grid(row=2+i,column=0,sticky=tk.W)

        self.lbl_areas = []
        for i in range(0, len(self.samples)):
            self.lbl=tk.IntVar()
            self.lbl.set(0)
            self.lbl_areas.append(tk.Label(self.win,textvariable=self.lbl).grid(row=2+i,column=1,sticky=tk.W))  

    def print_area(self, event):
        """Prints the values"""

        widget = event.widget
        selection=widget.curselection()
        value = widget.get(selection[0])

        #Here is the dictionary that maps time with values
        self.d = {1:[('a',33464.1),('b',43.5),('c',64.3)],
             2:[('a',5.1),('b',3457575.5),('c',25.3)],
             3:[('a',12.1),('b',13.5),('c',15373.3)]}

        lbl_val = []
        for i in range(0, len(self.samples)):
            lbl_val.append(self.d[value][i][1])


        for i in range(0, len(self.samples)):
            self.lbl=tk.IntVar()
            self.lbl.set(lbl_val[i])
            tk.Label(self.win,textvariable=self.lbl).grid(row=2+i,column=1,sticky=tk.W)         


 def main():
     root = tk.Tk()
     app = Plot(root)
     tk.mainloop()

 if __name__ == '__main__':
     main()

如果您尝试运行此代码并单击LOAD,您将看到列表框中出现的数字,并标注a,b,c,其值在开头设置为零。如果单击列表框中的数字,将显示值(映射到字典d),但您将看到覆盖问题。我该如何解决这个问题?

我该如何克服这个问题?谢谢

1 个答案:

答案 0 :(得分:1)

不要创建新标签。创建一次标签,然后使用标签的configure方法点击鼠标进行更新。

或者,在创建新标签之前删除旧标签。如果您设计应用程序以便所有这些临时标签都在一个框架中,您可以删除并重新创建框架,框架中的所有标签将自动获取删除。在任何一种情况下(破坏框架或破坏单个标签),您都会在要销毁的小部件上调用destroy方法。