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