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
The method to call is indeed
destroy, on thepopobject.However, inside of the
yesButtonmethod,poprefers to something that is unknown.When initializing your object, in the
__init__method, you should put thepopitem as an attribute ofself:Then, inside of your
yesButtonmethod, call thedestroymethod on theself.popobject:About the difference between
pop.destroyandpop.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, nameddestroy, and belonging to thepopobject. It's basically the same as writing1or"hello": it's not a statement, or if you prefer, not an action.When you write
pop.destroy(), you tell Python to call thepop.destroyobject, that is, to execute its__call__method.In other words, writing
pop.destroywill do nothing (except for printing something like<bound method Toplevel.destroy of...>when run in the interactive interpreter), whilepop.destroy()will effectively run thepop.destroymethod.