Python 3.x tkinter:如何编写for循环来销毁标签列表?
我正在尝试从网格中删除这些元素。我可以一个接一个地把它们都删掉。然后我写了一个for循环,使其可扩展,然后我遇到了这个错误消息Python 3.x tkinter:如何编写for循环来销毁标签列表?,python-3.x,for-loop,tkinter,label,destroy,Python 3.x,For Loop,Tkinter,Label,Destroy,我正在尝试从网格中删除这些元素。我可以一个接一个地把它们都删掉。然后我写了一个for循环,使其可扩展,然后我遇到了这个错误消息 "employee.destroy() AttributeError: 'str' object has no attribute 'destroy'" 这是一个更大程序的一部分,但我可以将其归结为核心问题,以下是我的代码: import tkinter as tk from tkinter import ttk labelemployee={} class Ap
"employee.destroy()
AttributeError: 'str' object has no attribute 'destroy'"
这是一个更大程序的一部分,但我可以将其归结为核心问题,以下是我的代码:
import tkinter as tk
from tkinter import ttk
labelemployee={}
class Application(ttk.Frame): #inherent from frame.
def __init__(self, parent):
tk.Frame.__init__(self, parent, bg="LightBlue4")
self.parent = parent
self.Employees = ["A", "B", "C", "D"]
self.pack(fill=tk.BOTH, expand=1)
self.GUI()
def GUI(self): #the function that runs all the GUI functions.
self.buttons()
self.create_grid()
self.add_left_names()
def remove(self):
#labelemployee["A"].destroy()
#labelemployee["B"].destroy()
#labelemployee["C"].destroy()
#labelemployee["D"].destroy()
for employee in labelemployee:
employee.destroy()
def create_grid(self):
for i in range (7):
for j in range(7):
self.label = tk.Label(self, relief="ridge", width=12,
height=3)
self.label.grid(row=i, column=j, sticky='nsew')
def buttons(self):
self.button=tk.Button(self, text="Clear", bg="salmon", command
= self.remove)
self.button.grid(row=7, column=6, sticky='e')
def add_left_names(self):
#--------add in name labels on the side--------------
i=2
for employee in self.Employees:
self.label=tk.Label(self, text=employee , fg="red",
bg="snow")
self.label.grid(row=i,column=0)
labelemployee[employee]=self.label
i +=1
def main():
root = tk.Tk()
root.title("class basic window")
root.geometry("1000x500")
root.config(background="LightBlue4")
app = Application(root)
root.mainloop()
if __name__ == '__main__':
main()
请帮帮我。我想问题是我的for循环存储在一个列表中,我有一个字典。所以,我猜我不知道如何销毁字典中的标签 您已经在这些评论中找到了问题所在
您已经知道
labelemployee
是一个字典,因此在默认情况下,迭代它将为您提供字典的键。所以employee
将是像A、B。。。等等销毁字符串对象显然会给您带来错误。您需要销毁相应的tkinter小部件。因此,您应该在for循环中将employee.destroy()
替换为labeleemployee[employee].destroy()
。谢谢您的帮助。我对如何编写代码感到困惑。我弄得很慢。既然你帮我弄了这个,麻烦你帮我弄一下好吗。看来没有人在帮我。我真的很感激。