Reputation: 139
I'm trying to make two buttons in Tkinter using python version 3.3, one to create a button and one to delete said button. It has been working so far except for the fact that if I create more than one button I can only delete one the the created buttons. My question is: is there anything I can do to be able to delete a button every time the delete button is called upon? This is my code so far:
from tkinter import *
def createbutton():
global secondbut
secondbut=Button(root,text="button")
secondbut.pack()
def eliminatebutton():
secondbut.destroy()
if __name__=='__main__':
root=Tk()
global create
global delete
create= Button(root,text="create",command=createbutton)
delete=Button(root,text="delete",command=eliminatebutton)
create.pack()
delete.pack()
root.mainloop()
Upvotes: 0
Views: 76
Reputation: 6031
The problem is that you're storing your Button
in a variable (secondbut
), then overwriting that variable if you create a new button.
Instead of directly storing it in a variable, store it in some container, such as a list.
This code will do what you want:
from tkinter import *
def createbutton():
global secondbut
secondbut.append(Button(root,text="button"))
secondbut[-1].pack()
def eliminatebutton():
secondbut[-1].destroy()
secondbut.pop()
if __name__=='__main__':
root=Tk()
global create
global delete
global secondbut
secondbut = []
create= Button(root,text="create",command=createbutton)
delete=Button(root,text="delete",command=eliminatebutton)
create.pack()
delete.pack()
root.mainloop()
Note that it removes buttons in the opposite order it adds them.
Upvotes: 1