Matriox
Matriox

Reputation: 13

How to forget buttons created by a loop?

I need to create buttons with a for loop, here its an example of what i need to do:

But the problem is that when I press the different buttons, its prints the correct number, but it only forgets the last button created (in this case the button "4"). How can i do to forget all the buttons at once by only pressing one of them?

Its important the creation of the buttons by the loop

import tkinter as tk
root=tk.Tk()
def Eliminate(Number):        
    def Forget(number):
        button.pack_forget()
        print(number)
    for i in range(Number):
        button= tk.Button(root,text=i,command=lambda number=i:Forget(number))
        button.pack()
        
Eliminate(5)
root.mainloop() ``` 


Upvotes: 1

Views: 141

Answers (1)

Novel
Novel

Reputation: 13729

You need to pass in the button widget itself, not the number that created it. To do that you simply need to issue the command argument in a new line, like this:

import tkinter as tk

def Forget(btn):
    btn.pack_forget()

def Eliminate(Number):
    for i in range(Number):
        button= tk.Button(root,text=i)
        button.config(command=lambda button=button:Forget(button))
        button.pack()

root=tk.Tk()
Eliminate(5)
root.mainloop()

However as the command is only calling the pack_forget method, it's much easier to forget making your own callback function and just provide pack_forget:

import tkinter as tk

def Eliminate(Number):
    for i in range(Number):
        button= tk.Button(root,text=i)
        button.config(command=button.pack_forget)
        button.pack()

root=tk.Tk()
Eliminate(5)
root.mainloop()

Upvotes: 1

Related Questions