0

In creating a Python Tkinter program, I wish to create a button that will close the program. I have tried the

#with master = Tk()
master.quit()

method. And it did absolutely nothing to my program - apart from stopping anything from working, although I received no Tracebacks.

The other method I have tried is:

#with master = Tk()
master.destroy()

This again did nothing to my program - it did give me a traceback error though which was:

_tkinter.TclError: can't invoke "button" command: application has been destroyed

My full code is:

from tkinter import *
master = Tk()

exitbutton = Button(master,text="Exit",(all the other personalization stuff here),command=(master.quit())) 
#or I used master.destroy() in the command area.
exitbutton.grid(column=0,row=0)

None of the above methods have worked.

Many Thanks (For the future)

3 Answers3

0

You must pass the function's name rather than as a callable:

from tkinter import *
master = Tk()

exitbutton = Button(master,text="Exit",command=master.destroy)##dont include the parentheses
##or I used master.destroy() in the command area.
exitbutton.grid(column=0,row=0)

This should fix your problem.

TheFluffDragon9
  • 514
  • 5
  • 11
0

Problem:

  • The only problem is that you are using parentheses() while passing the function(exit or destroy) to the Button as a command, Which causes it to be executed at the point where it is defined.

Solution:

  • The solution is to remove the parentheses() while passing the function(exit or destroy) to the Button as a command.

Fixed Code:

from tkinter import *

master = Tk()

exitbutton = Button(master, text="Exit", command=master.quit)   # you can also use master.destroy
exitbutton.grid(column=0, row=0)

master.mainloop()

Tip:

  • As importing all(*) is not a good practice, you should import tkinter as tk or as anything you want. The only change you will is to add tk. before each object belonging to tkinter.

Then your code will be as follows.

Best Practice:

import tkinter as tk
master = tk.Tk()

exitbutton = tk.Button(master, text="Exit", command=master.quit)   # you can also use master.destroy
exitbutton.grid(column=0, row=0)

master.mainloop()
DaniyalAhmadSE
  • 807
  • 11
  • 20
-1

You want to pass a function object into the command keyword, so don't use parentheses. Also you should be using the destroy function for TKinter.

exitbutton = Button(master,text="Exit",(all the other personalization stuff here),command=master.destroy)