在tkinter中使用For循环删除/创建标签

时间:2019-03-15 15:33:54

标签: tkinter

我打算使用for循环创建标签。每次我从组合框中选择一个不同的选项时,较旧的标签都应删除,并应创建新的标签。我使用以下代码,但出现错误。

我使用python 3.7.2

import tkinter as tk
from tkinter import ttk
master = tk.Tk()

class job():
    def fun(self,eventObject):
        print(self.box_value.get())
        dimensions = ['ab', 'bc','cd','de']
        self.labl.destroy()
        z = 20
        for i in range(len(dimensions)):
            self.labl = tk.Label(master, text=dimensions[i])
            self.labl.place(x=z, y=20)
            z = z + 130
    def __init__(self):
        self.box_value=tk.StringVar()
        self.combo = ttk.Combobox(master, textvariable=self.box_value, state='readonly')
        self.combo['values'] = ['Cd', 'Ale']
        self.combo.bind("<<ComboboxSelected>>", self.fun)
        self.combo.current(1)
        self.combo.place(x=80,y=100)

a=job()

master.mainloop()
  

AttributeError:“ job”对象没有属性“ labl”

1 个答案:

答案 0 :(得分:1)

我自己管理它,以前我无法获得实现它的逻辑。但现在我很好,发布答案以供将来参考:

import tkinter as tk
from tkinter import ttk
master = tk.Tk()

class job():
    def fun(self,eventObject):
        dimensions = ['gdgd','dfddf','bgsdg']
        try:
            if self.check == 1:
                for i in self.labels:
                    i.destroy()
        except:
            pass
        z = 20
        self.labels=[]
        for i in range(len(dimensions)):
            self.labl = tk.Label(master, text=dimensions[i])
            self.labl.place(x=z, y=20)
            self.labels.append(self.labl)
            z = z + 130
    self.check = 1
def __init__(self):
    self.box_value=tk.StringVar()
    self.combo = ttk.Combobox(master, textvariable=self.box_value, state='readonly')
    self.combo['values'] = ['ab', 'bc', 'cd']
    self.combo.bind("<<ComboboxSelected>>", self.fun)
    self.combo.current(1)
    self.combo.place(x=80,y=100)

a=job()

master.mainloop()