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 thepop
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 thepop
item as an attribute ofself
:Then, inside of your
yesButton
method, call thedestroy
method on theself.pop
object:About the difference between
pop.destroy
andpop.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 thepop
object. It's basically the same as writing1
or"hello"
: it's not a statement, or if you prefer, not an action.When you write
pop.destroy()
, you tell Python to call thepop.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), whilepop.destroy()
will effectively run thepop.destroy
method.