Я пытаюсь создать кнопки, которые удаляют себя. В приведенном ниже коде я создаю несколько кнопок в цикле 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()
Спасибо!
Зачем вам хранить их в списке? – tzaman
У меня была такая же проблема на днях, когда я пытался найти индекс кнопки в списке после ее нажатия. –