如何解决在python中制作可调整的tkinter按钮列表的最佳方法是什么?
我正在尝试制作一个将存储的数字或方程式存储到字符串列表中的计算器应用程序。我还试图创建一个辅助窗口,为每个内存条目显示一个删除按钮和一个标签。我正在为它们使用按钮列表和标签列表,并且试图匹配所有3个列表的索引。
按下删除按钮时,我要在所有三个列表中弹出相同的索引,然后将按下的按钮及其对应的标签设为.destroy()。 Windows 10计算器应用程序中提供了此功能的示例。但是,我知道,如果我弹出一个索引,则该索引之后的索引将成为该索引,因此您不能只为每个按钮分配一个固定的索引。因此,我想主要的问题是,如何获取特定按钮的当前索引,并使用该索引来确定要在其他两个列表中删除的字符串和标签?我尝试在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()
解决方法
好,所以我弄清楚了如何使按钮适应性强。我需要做两件事:
-
在弹出索引后,我需要将索引重新分配给按钮上的command属性。因此,我首先创建了一个for循环,该循环遍历按钮列表,并将索引从0开始重新分配给其命令属性。这样可以确保所有按钮始终具有更新的命令属性,就像以前一样,如果它们弹出之前的索引,它们总是试图引用不再是它们的索引。
-
我需要在每个按钮的command属性中的lambda中写入一个参数。命令为lambda c = i:memDestroyer(c)。这是因为循环结束后,我将始终等于列表的最后一个索引,因此您可以看到这将是一个问题。但是,通过使用c = 1,c不是i,它可以保存在一次特定迭代中i曾经等于的值,因此它允许每个按钮都有自己的索引分配。
下面是代码:
def memDestroyer(index):
if memBank.__len__() and memDeleteButtons.__len__() and memLabels.__len__() > 0:
print(f"index is {index}")
memLabels[index].destroy()
memDeleteButtons[index][0].destroy()
memLabels.pop(index)
memBank.pop(index)
memDeleteButtons.pop(index)
step = 0
for i in memDeleteButtons:
print(f"Pointer index is {step}")
i[0].config(command=lambda c = step: memDestroyer(c))
step += 1
else:
return
def memMenu():
print(memBank)
global root1
root1 = Tk()
root1.title("Saved Equations")
root1.geometry("300x600")
index = 0
row_index = 1
for i,v in enumerate(memBank):
print("loop began")
if v == "":
memBank.pop(i)
continue
elif i >= memBank.__len__():
break
else:
global button
if memDeleteButtons.__len__() - 1 and memLabels.__len__() - 1 >= i:
memDeleteButtons.pop(i)
memLabels.pop(i)
memLabels.insert(i,Label(root1,text=v))
memLabels[i].grid(row=row_index,column=2)
memDeleteButtons.insert(i,[Button(root1,text="x",command=lambda c = i:memDestroyer(i))])
memDeleteButtons[i][0].grid(row=row_index,column=1)
# import logging
# open("Calculator.txt")
index += 1
row_index += 1
print(i)
root1.mainloop()
return
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。