-2

How to close a tkinter Toplevel window after pressing a button? I have already associated a command on the button, so I can't destroy the window.

I have more than one Toplevel in my class

antonio
  • 59
  • 6
  • 1
    Call `destroy()` on the `Toplevel` window. Also show what have you done so far. – Saad May 09 '19 at 10:40
  • 1
    you have to assign Toplevel to global (or class) variable so you could access it in other place. And then you can do `window.destroy()`. If you have many windows then you have to assign every window to separated variable or keep all of them on list. – furas May 09 '19 at 10:40
  • @furas This is what I did. but I thought there was a smarter way to do it – antonio May 09 '19 at 11:45
  • What do you mean "smarter"? Why is saving a reference and then calling `destroy` on that reference not smart enough? Can you show some code that illustrates the problem that you're having? – Bryan Oakley May 10 '19 at 20:41

1 Answers1

0

If your top window button must do stuff, then quit, you can call top.destroy after doing the stuff:

Maybe something like this:

import tkinter as tk

def do_that_and_close(top):
    print('doing that')
    top.destroy()

def launch_top():
    top = tk.Toplevel(root)
    lbl = tk.Label(top, text='this is top')
    lbl.pack()    
    btn = tk.Button(top, text='do this and quit', command=lambda: do_that_and_close(top))
    btn.pack()

root = tk.Tk()
lbl = tk.Label(root, text='this is root')
lbl.pack()
root_btn = tk.Button(root, text='launch top', command=launch_top)
root_btn.pack()
quit_btn = tk.Button(root, text='quit', command=root.destroy)
quit_btn.pack()

root.mainloop()
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • You are welcome, I am glad I could help, If you feel that my answer helped you, you could consider [what to do when someone answers my question](https://stackoverflow.com/help/someone-answers), and [how to accept my answer](http://meta.stackexchange.com/a/5235) – Reblochon Masque May 15 '19 at 06:52