1 回答
TA贡献1860条经验 获得超9个赞
你创建了一个Label命名文件self.item,然后不断地覆盖它,期望它神奇地成为一个新的Label. 修复方法很简单~不要创建self.item. 相反,创建一个列表并Labels根据需要将新内容推送到其中。这为您的删除方法奠定了基础,因为您可以解压缩缓存中的所有内容,删除所需的项目并重新打包缓存中剩余的所有内容。我的例子在重要的地方进行了评论。我没有给你写删除方法。
import tkinter as tk
root = tk.Tk()
root.title("To Do")
root.geometry("500x750")
root.resizable(False, False)
class App:
def __init__(self, window):
#Button font
self.buttonFont = ("Courier", 13, "normal")
#Header
self.header = tk.Label(text = "To Do List\n", font = ("Helvetica", 26, "bold"))
self.header.grid()
#Add item button
self.addButton = tk.Button(text = "Add Item", font = self.buttonFont, bg = "green", command = self.OpenAddItem)
self.addButton.grid(row = 1, column = 0, )
#Del item button
self.delButton = tk.Button(text = "Delete Item", font = self.buttonFont, bg = "red")
self.delButton.grid(row = 1, column = 1, )
#items frame and stuff
self.itemsframe = tk.Frame()
self.itemsframe.grid(row = 2)
''' you just keep overwriting this '''
#self.item = tk.Label(self.itemsframe, font = ("Helvetica", 11, "normal"))
#start a cache instead
self.items = []
def OpenAddItem(self):
#COnfiguring prompt win
self.addPromptWin = tk.Toplevel(root)
self.addPromptWin.title("Prompt")
self.addPromptWin.geometry("375x100")
self.addPromptWin.resizable(False,False)
#Entry label
self.entryLabel = tk.Label(self.addPromptWin,text = "Enter item name:", font = ("Courier", 11, "normal"))
self.entryLabel.grid(sticky = tk.E)
#Adding entry
self.entry = tk.Entry(self.addPromptWin, font = ("Courier", 11, "normal"))
self.entry.grid(row = 0, column = 1)
self.entry.bind("<Return>", lambda e: self.AddItem())
#Add new item button
self.addNewItemButton = tk.Button(self.addPromptWin, text = "Add", font = self.buttonFont, bg = "green", command = self.AddItem)
self.addNewItemButton.grid(row = 1, sticky = tk.W)
def AddItem(self):
self.entryValue = self.entry.get()
'''
you can keep configuring and repacking this for infinity
it's not going to change the fact that it's the same label every time
'''
#self.item.config(text = f"1. {self.entryValue}")
#self.item.pack()
#append a new label to the cache instead
self.items.append(tk.Label(self.itemsframe, font = ("Helvetica", 11, "normal"), anchor='w'))
#config and pack the last item in the cache
self.items[-1].config(text = f"{len(self.items)}. {self.entryValue}",)
self.items[-1].pack(anchor='w')
self.addPromptWin.destroy()
app = App(root)
root.mainloop()
添加回答
举报