python - Python,从按钮列表中删除项目
问题描述
所以我有这段代码可以在电子表格中读取数据框,然后我有两个在按下按钮时运行的函数。第一个为数据框中的每一列创建一个新按钮列表。第二个是清除按钮列表并从屏幕上删除按钮。
我有两个问题。首先,第一个函数中按钮的构建工作正常,但列表很奇怪。在我的示例数据中,有四列。按钮从“...button”开始,然后是“...button2”、“...button3”、“...button4”。我不知道为什么没有 0,1,2,3 或 1,2,3,4。
然后,当我在第二个功能中删除按钮时,当它到达第三个按钮时它会崩溃。不知道为什么。我既要从网格中删除按钮,又要将它们从按钮列表中删除。我尝试清除整个列表,而不是在遍历列表时删除每个按钮,但这并没有奏效。我尝试了几种方法,如下:
self.column_buttons = []
del self.column_buttons[:]
self.column_buttons.clear()
这些都不会清空列表。如果我建立按钮列表,然后使用上述任何方法尝试清除它,然后再次构建它,ist 中的按钮是 5-8,重新清除和重新构建然后让我得到 9-12,等等上。
这是我的代码....
def fxThree(self):
print(self.column_buttons)
# make a new button in a new frame for each column in the file
for x in range(len(self.df1_columns)):
self.new_button = tk.Button(self.frame3, text=self.df1_columns[x], command=lambda x=x: delete_button(self, x))
self.new_button.grid(row=10, column=(x))
self.column_buttons.append(self.new_button)
print(self.column_buttons)
print("\n")
def fxFour(self):
for x in range(len(self.column_buttons)):
print(x)
print("Removing button: " + str(x))
self.column_buttons[x].grid_remove()
print("Deleting list entry :" + str(x))
del self.column_buttons[x]
del self.column_buttons[:]
print(self.column_buttons)
这是第一个函数的输出在控制台中的样子:
[<tkinter.Button object .!frame3.!button>, <tkinter.Button object .!frame3.!button2>, <tkinter.Button object .!frame3.!button3>, <tkinter.Button object .!frame3.!button4>]
这是第二个函数的输出和错误:
0
Removing button: 0
Deleting list entry :0
1
Removing button: 1
Deleting list entry :1
2
Removing button: 2
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/user/Documents/Data Management/Python/SheetMapper/sheet_mapper_01.3.py", line 312, in fxFour
self.column_buttons[x].grid_remove()
IndexError: list index out of range
我什至尝试让它从最后一个条目开始向后迭代,以防我边走边抹掉条目,但仍然出现 not in index 错误。