Closing a Toplevel Tkinter window

5.2k views Asked by At

I'm trying to teach myself Python so apologies for what may be a stupid question but this has been driving me crazy for a few days. I've looked at other questions on the same subject here but still don't seem to be able to get this to work.

I have created a top level window to ask the user for a prompt and would like the window to close when the user presses the button of their choice. This is where the problem is, I can't get it to close for love or money. My code is included below.

Thank so much for any help.

from Tkinter import *

root = Tk()

board = Frame(root)
board.pack()

square = "Chat"
cost = 2000

class buyPrompt:

         def __init__(self):
            pop = Toplevel()

            pop.title("Purchase Square")

            Msg = Message(pop, text = "Would you like to purchase %s for %d" %                         (square, cost))
            Msg.pack()


            self.yes = Button(pop, text = "Yes", command = self.yesButton)
            self.yes.pack(side = LEFT)
            self.no = Button(pop, text = "No", command = self.noButton)
            self.no.pack(side = RIGHT)

            pop.mainloop()
         def yesButton(self):
                        return True
                        pop.destroy
         def noButton(self):
                        return False

I've tried quite a few different ways of doing pop.destroy but none seem to work, things I've tried are;

pop.destroy()
pop.destroy
pop.exit()
pop.exit

Thank you

1

There are 1 answers

1
Right leg On BEST ANSWER

The method to call is indeed destroy, on the pop object.

However, inside of the yesButton method, pop refers to something that is unknown.

When initializing your object, in the __init__ method, you should put the pop item as an attribute of self:

self.pop = Toplevel()

Then, inside of your yesButton method, call the destroy method on the self.pop object:

self.pop.destroy()

About the difference between pop.destroy and pop.destroy():

In Python, pretty much everything is an object. So a method is an object too.

When you write pop.destroy, you refer to the method object, named destroy, and belonging to the pop object. It's basically the same as writing 1 or "hello": it's not a statement, or if you prefer, not an action.

When you write pop.destroy(), you tell Python to call the pop.destroy object, that is, to execute its __call__ method.

In other words, writing pop.destroy will do nothing (except for printing something like <bound method Toplevel.destroy of...> when run in the interactive interpreter), while pop.destroy() will effectively run the pop.destroy method.