Tkinter exit error [duplicate] - python

How do I end a Tkinter program? Let's say I have this code:
from Tkinter import *
def quit():
# code to exit
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
How should I define the quit function to exit my application?

You should use destroy() to close a Tkinter window.
from Tkinter import *
#use tkinter instead of Tkinter (small, not capital T) if it doesn't work
#as it was changed to tkinter in newer Python versions
root = Tk()
Button(root, text="Quit", command=root.destroy).pack() #button to close the window
root.mainloop()
Explanation:
root.quit()
The above line just bypasses the root.mainloop(), i.e., root.mainloop() will still be running in the background if quit() command is executed.
root.destroy()
While destroy() command vanishes out root.mainloop(), i.e., root.mainloop() stops. <window>.destroy() completely destroys and closes the window.
So, if you want to exit and close the program completely, you should use root.destroy(), as it stops the mainloop() and destroys the window and all its widgets.
But if you want to run some infinite loop and don't want to destroy your Tkinter window and want to execute some code after the root.mainloop() line, you should use root.quit(). Example:
from Tkinter import *
def quit():
global root
root.quit()
root = Tk()
while True:
Button(root, text="Quit", command=quit).pack()
root.mainloop()
#do something
See What is the difference between root.destroy() and root.quit()?.

def quit()
root.quit()
or
def quit()
root.destroy()

import tkinter as tk
def quit(root):
root.destroy()
root = tk.Tk()
tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack()
root.mainloop()

Illumination in case of confusion...
def quit(self):
self.destroy()
exit()
A) destroy() stops the mainloop and kills the window, but leaves python running
B) exit() stops the whole process
Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to "end" a tkinter program.

I think you wrongly understood the quit function of Tkinter. This function does not require you to define.
First, you should modify your function as follows:
from Tkinter import *
root = Tk()
Button(root, text="Quit", command=root.quit).pack()
root.mainloop()
Then, you should use '.pyw' suffix to save this files and double-click the '.pyw' file to run your GUI, this time, you can end the GUI with a click of the Button, and you can also find that there will be no unpleasant DOS window. (If you run the '.py' file, the quit function will fail.)

The usual method to exit a Python program:
sys.exit()
(to which you can also pass an exit status) or
raise SystemExit
will work fine in a Tkinter program.

In case anyone wants to bind their Escape button to closing the entire GUI:
master = Tk()
master.title("Python")
def close(event):
sys.exit()
master.bind('<Escape>',close)
master.mainloop()

The easiest way would be to click the red button (leftmost on macOS and rightmost on Windows).
If you want to bind a specific function to a button widget, you can do this:
class App:
def __init__(self, master)
frame = Tkinter.Frame(master)
frame.pack()
self.quit_button = Tkinter.Button(frame, text = 'Quit', command = frame.quit)
self.quit_button.pack()
Or, to make things a little more complex, use protocol handlers and the destroy() method.
import tkMessageBox
def confirmExit():
if tkMessageBox.askokcancel('Quit', 'Are you sure you want to exit?'):
root.destroy()
root = Tk()
root.protocol('WM_DELETE_WINDOW', confirmExit)
root.mainloop()

you only need to type this:
root.destroy()
and you don't even need the quit() function cause when you set that as commmand it will quit the entire program.

you dont have to open up a function to close you window, unless you're doing something more complicated:
from Tkinter import *
root = Tk()
Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()

In idlelib.PyShell module, root variable of type Tk is defined to be global
At the end of PyShell.main() function it calls root.mainloop() function which is an infinite loop and it runs till the loop is interrupted by root.quit() function. Hence, root.quit() will only interrupt the execution of mainloop
In order to destroy all widgets pertaining to that idlelib window, root.destroy() needs to be called, which is the last line of idlelib.PyShell.main() function.

I normally use the default tkinter quit function, but you can do your own, like this:
from tkinter import *
from tkinter.ttk import *
window = Tk()
window.geometry('700x700') # 700p x 700p screen
def quit(self):
proceed = messagebox.askyesno('Quit', 'Quit?')
proceed = bool(proceed) # So it is a bool
if proceed:
window.quit()
else:
# You don't really need to do this
pass
btn1 = Button(window, text='Quit', command=lambda: quit(None))
window.mainloop()

For menu bars:
def quit():
root.destroy()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=quit)
menubar.add_cascade(label="menubarname", menu=filemenu)
root.config(menu=menubar)
root.mainloop()

I use below codes for the exit of Tkinter window:
from tkinter import*
root=Tk()
root.bind("<Escape>",lambda q:root.destroy())
root.mainloop()
or
from tkinter import*
root=Tk()
Button(root,text="exit",command=root.destroy).pack()
root.mainloop()
or
from tkinter import*
root=Tk()
Button(root,text="quit",command=quit).pack()
root.mainloop()
or
from tkinter import*
root=Tk()
Button(root,text="exit",command=exit).pack()
root.mainloop()

Code snippet below. I'm providing a small scenario.
import tkinter as tk
from tkinter import *
root = Tk()
def exit():
if askokcancel("Quit", "Do you really want to quit?"):
root.destroy()
menubar = Menu(root, background='#000099', foreground='white',
activebackground='#004c99', activeforeground='white')
fileMenu = Menu(menubar, tearoff=0, background="grey", foreground='black',
activebackground='#004c99', activeforeground='white')
menubar.add_cascade(label='File', menu=fileMenu)
fileMenu.add_command(label='Exit', command=exit)
root.config(bg='#2A2C2B',menu=menubar)
if __name__ == '__main__':
root.mainloop()
I have created a blank window here & add file menu option on the same window(root window), where I only add one option exit.
Then simply run mainloop for root.
Try to do it once

Of course you can assign the command to the button as follows, however, if you are making a UI, it is recommended to assign the same command to the "X" button:
def quit(self): # Your exit routine
self.root.destroy()
self.root.protocol("WM_DELETE_WINDOW", self.quit) # Sets the command for the "X" button
Button(text="Quit", command=self.quit) # No ()

There is a simple one-line answer:
Write - exit() in the command
That's it!

Related

Change right click event of tkinter command

I want to detect the right click event on tkinter Menu command.
Consider code below.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
menu_button = ttk.Menubutton(root, text="MENU")
menu_button.grid()
m = tk.Menu(menu_button, tearoff=False, activeborderwidth=0)
menu_button["menu"] = m # To avoid garbage collection
m.add_command(label="an option", command=lambda: print("option1"))
m.add_command(label="another option", command=lambda: print("option2"))
root.mainloop()
When I click an option or another option, the commands are called as expected. But want I want to do is catch right click event. Can anyone knows that how can I detect it?
use button.bind("<Button-3>", event). Consider this code:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
button = tk.Button(root, text='right click this')
button.pack()
button.bind("<Button-3>", lambda e: print('You right clicked'))
root.mainloop()

Is it possible to reopen tkinter window after closing it whose code written in separate file OnClicking button from file?

filename p1.py
import tkinter as tk
def action():
import p2
root=tk.Tk()
root.title('part1')
root.geometry('200x200+50+50')
btn=tk.Button(root,text='click me',command=action)
btn.pack()
root.mainloop()
filename p2.py
After closing this window, I want to reopen it on clicking the click me button but it does not open once I close this window.
import tkinter as tk
root=tk.Toplevel()
root.title('part2')
root.geometry('200x200+50+50')
lbl=tk.Label(root,text='Hello everybody \n I have problem',font=("times new roman",20,'bold'))
lbl.pack()
root.mainloop()
Here's a solution for you:
Module_one:
import tkinter as tk
def action():
import action_module
action_module.page_two()
root = tk.Tk()
root.title('part1')
root.geometry('200x200+50+50')
btn = tk.Button(root, text='click me', command=action)
btn.pack()
root.mainloop()
action_module:
def page_two():
import tkinter as tk
root = tk.Toplevel()
root.title('part2')
root.geometry('200x200+50+50')
lbl = tk.Label(root, text='Hello everybody \n I think the problem is fixed',
font=("times new roman", 20, 'bold'))
lbl.pack()
root.mainloop()
Just put the code in the second module inside a function. Then call it inside the first file's action function.

Tkinter: Bind <Enter> event to entire window (but not all widgets)

My goal is to bind an Event to the window. For example I want a function called when the mouse pointer enters the window. The code below does this but sadly the function is also called whenever the mouse pointer enters the Button. I tried B.unbind("<Enter>") but it does not work. Any help would be appreciated
import tkinter as tk
root = tk.Tk()
def function(event):
print("Hello World")
B = tk.Button(root, text ="Label")
root.bind("<Enter>",function)
root.geometry("100x100")
B.pack()
root.mainloop()
One way to make this work is to check for event.widget and see if it is the root window, which is a instance of Tk.
import tkinter as tk
root = tk.Tk()
def function(event):
if isinstance(event.widget,tk.Tk): #check if event widget is Tk root window
print("Hello World")
B = tk.Button(root, text ="Label")
root.bind("<Enter>",function)
root.geometry("100x100")
B.pack()
root.mainloop()

How to only close TopLevel window in Python Tkinter?

Use the Python Tkinter , create a sub-panel (TopLevel) to show something and get user input, after user inputed, clicked the "EXIT" found the whole GUI (main panel) also destory.
How to only close the toplevel window?
from tkinter import *
lay=[]
root = Tk()
root.geometry('300x400+100+50')
def exit_btn():
top = lay[0]
top.quit()
top.destroy()
def create():
top = Toplevel()
lay.append(top)
top.title("Main Panel")
top.geometry('500x500+100+450')
msg = Message(top, text="Show on Sub-panel",width=100)
msg.pack()
btn = Button(top,text='EXIT',command=exit_btn)
btn.pack()
Button(root, text="Click me,Create a sub-panel", command=create).pack()
mainloop()
This seemed to work for me:
from tkinter import *
lay=[]
root = Tk()
root.geometry('300x400+100+50')
def create():
top = Toplevel()
lay.append(top)
top.title("Main Panel")
top.geometry('500x500+100+450')
msg = Message(top, text="Show on Sub-panel",width=100)
msg.pack()
def exit_btn():
top.destroy()
top.update()
btn = Button(top,text='EXIT',command=exit_btn)
btn.pack()
Button(root, text="Click me,Create a sub-panel", command=create).pack()
mainloop()
Your only mistake is that you're calling top.quit() in addition to calling top.destroy(). You just need to call top.destroy(). top.quit() will kill mainloop, causing the program to exit.
You can't close to root window. When you will close root window, it is close all window. Because all sub window connected to root window.
You can do hide root window.
Hide method name is withdraw(), you can use show method for deiconify()
# Hide/Unvisible
root.withdraw()
# Show/Visible
root.deiconify()
you can use lambda function with the command it's better than the normal function for your work
ex)
btn = Button(top,text='EXIT',command=exit_btn)
change the exit_btn to lambda :top.destroy()
In my case, I passed a callback function from the parent class, and once the submit button is clicked it will the callback function passing the return values.
The callback function will call the destroy method on the top-level object, thus in that way you'll close the frame and have the return value.

Tkinter: messagebox doesn`t work right. (get two windows)

I am using python 3.
If I opan an error messagebox, i get two frames, one is emty and one is the error-window. That is my code:
from tkinter import messagebox
messagebox.showwarning('warning', 'warning')
Everything works correctly in your example. The empty window is the main window of Tk. It is always open when you start any Tk program. You can minimize it if you want, but closing it terminates the main loop.
Try this:
root = tkinter.Tk()
root.withdraw()
messagebox.showwarning('warning', 'warning')
Thank you DYZ,
in my code is no main window, (eg.: main = Tk() ... main.mainloop), because of that the warning massage create one. I could solve the problem by create one and minimize it. at the end of massagebox I destroyed it to continue in code.
from tkinter import *
from tkinter import messagebox
main = Tk()
main.geometry("500x400+300+300")
def message():
main.geometry("0x0")
messagebox.showwarning("Say Hello", "Hello World")
main.destroy()
B1 = Button(main, text = "Start Dialog",fg="dark green", command = message)
B1.pack()
main.mainloop()
print("finish dialog")

Categories

Resources