【发布时间】:2015-12-07 14:52:01
【问题描述】:
我正在尝试创建可自行删除的按钮。在下面的代码中,我在 for 循环中创建了一些按钮,将它们附加到列表中,并将它们网格化。我可以在按钮列表的某个索引位置删除和移除任何按钮,但需要弄清楚如何让每个按钮在按钮列表中定位自己。
from tkinter import *
import random
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.totalButtons = random.randint(5, 25)
# The buttons will be stored in a list
self.buttons = []
self.labels = []
self.createButtons()
def createButtons(self):
for i in range(0, self.totalButtons):
# Here I create a button and append it to the buttons list
self.buttons.append(Button(self, text = i, command = self.removeButton))
# Now I grid the last object created (the one we just created)
self.buttons[-1].grid(row = i + 1, column = 1)
# Same thing for the label
self.labels.append(Label(self, text = i))
self.labels[-1].grid(row = i + 1, column = 0)
def removeButton(self):
# When a button is clicked, buttonIndex should be able to find the index position of that button in self.buttons
# For now I set it to 0, which will always remove the first (top) button
indexPosition = 0
# Takes the button (in this case, the first one) off the grid
self.buttons[indexPosition].grid_forget()
# Removes that button from self.buttons
del self.buttons[indexPosition]
# Same for the label
self.labels[indexPosition].grid_forget()
del self.labels[indexPosition]
def main():
a = App()
a.mainloop()
if __name__ == "__main__":
main()
谢谢!
【问题讨论】:
-
为什么需要将它们存储在列表中?
-
前几天我遇到了完全相同的问题,试图在按下按钮后在列表中找到按钮的索引。
标签: python arrays python-3.x tkinter