【发布时间】:2021-01-09 20:22:58
【问题描述】:
我正在尝试制作一个计算器应用程序,将记忆的数字或方程式存储到字符串列表中。我还尝试创建一个辅助窗口,显示删除按钮和每个内存条目的标签。我正在为它们使用按钮列表和标签列表,并且我正在尝试匹配所有 3 个列表的索引。
当按下删除按钮时,我想在所有三个列表中 .pop 相同的索引,并 .destroy() 按下的按钮及其对应的标签。此功能的一个示例是在 Windows 10 计算器应用程序中。但是,我知道如果我弹出一个索引,它之后的索引就会变成那个索引,所以你不能只为每个按钮分配一个固定的索引。所以我想主要问题是,如何获取特定按钮的当前索引并使用它来确定在其他 2 个列表中删除哪个字符串和标签?我尝试在 memDeleteButtons.index(self) 中使用 self,但由于某种原因它无法解决任何问题。
下面是我正在处理的代码:
def memDestroyer(index):
if memBank.__len__() and memDeleteButtons.__len__() and memLabels.__len__() > 0:
memLabels[index].destroy()
memDeleteButtons[index].destroy()
memLabels.pop(index)
memBank.pop(index)
memDeleteButtons.pop(index)
else:
return
def memMenu():
print(memBank)
global root1
root1 = Tk()
root1.title("Saved Equations")
root1.geometry("300x600")
index = 0
for i in memBank:
print("loop began")
if i == "":
memBank.pop(memBank.index(i))
continue
elif index >= memBank.__len__():
break
else:
memLabels.append(Label(root1, text=i))
memLabels[-1].pack()
memDeleteButtons.append(Button(root1, text="x"))
memDeleteButtons[-1].config(command=lambda:memDestroyer(memDeleteButtons.index(self)))
memDeleteButtons[-1].pack()
index += 1
print("loop ended")
root1.mainloop()
【问题讨论】:
-
您可以使用按钮、标签和字符串存储元组列表。
-
非常感谢!所以对于按钮,它将是一个元组列表,每个元组都包含按钮和字符串形式的按钮对象 id。使用语法 memDeleteButtons.index((button, objectID)) 检查对象 ID 的位置是否正确?我会做一个测试。
标签: python list tkinter calculator