Tkinter quit freezes
Question:
I have written a very simple snippet of code just to try tkinter
:
import tkinter as tk
root=tk.Tk()
frame = tk.Frame(root).pack()
button = tk.Button(frame,
text="next",
command=root.quit).pack()
root.mainloop()
The above code causes the window to freeze. Could someone explain to me what is the reason behind this behaviour?
Answers:
Seperating the pack()
from the initialisation lines will fix your issue.
import tkinter as tk
root=tk.Tk()
frame=tk.Frame(root)
frame.pack()
button = tk.Button(frame,text="next",command=root.quit)
button.pack()
root.mainloop()
Too late in the game, but I had this similar problem before. I was using Jupyter Notebook to run the code.
Instead of using command=root.quit
, use command=root.destroy
. I’m not an expert, but if I understand correctly root.quit
attempts to quit the IDE too, whereas root.destroy
will only exit the Tkinter window.
I had the same issue.
I am using Python 3.7 and Spyder. The main issue was Spyder, not the code.
I changed to Jupyter Notebook and it worked.
Making .pack()
or .grid()
a separate line didn’t work for me. The solution was to hide the window using root.withdraw()
before running root.quit()
or root.destroy()
as shown below.
import tkinter as tk
def quit_(root):
root.withdraw()
root.quit()
root = tk.Tk()
tk.Button(root, text="Quit", command=lambda: quit_(root)).pack()
root.mainloop()
I have written a very simple snippet of code just to try tkinter
:
import tkinter as tk
root=tk.Tk()
frame = tk.Frame(root).pack()
button = tk.Button(frame,
text="next",
command=root.quit).pack()
root.mainloop()
The above code causes the window to freeze. Could someone explain to me what is the reason behind this behaviour?
Seperating the pack()
from the initialisation lines will fix your issue.
import tkinter as tk
root=tk.Tk()
frame=tk.Frame(root)
frame.pack()
button = tk.Button(frame,text="next",command=root.quit)
button.pack()
root.mainloop()
Too late in the game, but I had this similar problem before. I was using Jupyter Notebook to run the code.
Instead of using command=root.quit
, use command=root.destroy
. I’m not an expert, but if I understand correctly root.quit
attempts to quit the IDE too, whereas root.destroy
will only exit the Tkinter window.
I had the same issue.
I am using Python 3.7 and Spyder. The main issue was Spyder, not the code.
I changed to Jupyter Notebook and it worked.
Making .pack()
or .grid()
a separate line didn’t work for me. The solution was to hide the window using root.withdraw()
before running root.quit()
or root.destroy()
as shown below.
import tkinter as tk
def quit_(root):
root.withdraw()
root.quit()
root = tk.Tk()
tk.Button(root, text="Quit", command=lambda: quit_(root)).pack()
root.mainloop()