0
我在for循环中创建标签,每当我在应用程序上触发事件(单击鼠标)时显示整数。问题在于旧标签不会被删除,而新标签会导致混乱。 这里是工作的代码,你可以尝试一下:Tkinter:将整数作为标签覆盖
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),但您会看到覆盖问题。我该如何解决这个问题?
我该如何克服这个问题?谢谢
如何删除旧标签?我试图在for循环结束时使用self.lbl.destroy(),但这并不能解决问题。谢谢你的帮助! – diegus
@diegus:你在标签上调用'destroy'方法。如果那不起作用,你做错了。没有看到实际的代码,就不可能说出你做错了什么。 –
@Oakley我做了一个包含应用程序的一部分的编辑(希望这有帮助),我应该在哪里调用destroy方法? – diegus