0

I'm aware of this discussion: (How do I close a tkinter window?)

I'm curious as to how this changes when doing the same thing in a Jupyter notebook.

test code:

from tkinter import *

def close_window():
    root.destroy()
    #exit()

root = Tk()

#root.protocol("WM_DELETE_WINDOW", close_window)

Button(root, text="Close", command=close_window).pack()

root.mainloop()

Works fine when I run the script from the command line. Running it from a Jupyter notebook hangs when trying to close the tkinter window (using the root.protocol doesn't change anything).

If I include the exit(), the window does close, but the kernel dies. Is there a way to close the tkinter window and not have the kernel die? After investigating this for quite a while, it seems like the outcomes are mutually exclusive. I'm hoping for an explanation that's more than "that's just the way it is" for the benefit of students. Or, a workaround. In my fantasy world, the Jupyter code cell can be run repeatedly, closing the window each time, without the kernel dying.

Apologies for formatting issues – I rarely post to stackoverflow...

jeglin
  • 1

1 Answers1

0

Try to add %%python before your code.

It will look like this:

%%python
from tkinter import *

def close_window():
    root.destroy()

root = Tk()

Button(root, text="Close", command=close_window).pack()

root.mainloop()

This question is similar to yours: Tkinter crashes Jupyter kernel?

iglebov
  • 25
  • 6
  • Yes this actually does fix it (I had found that link as well earlier), which is confusing, because that cell magic just makes all code be interpreted as Python. But it already is Python (?). I didn't bring this up though because this magic causes another issue. A more complex version of the code also prints to the console either via a button or key press, and when I include %%python, none of that print output appears until after the exit. It gets buffered somewhere and then is all spit out after the fact. If I could fix THAT problem, then I could indeed use %%python. – jeglin Mar 18 '23 at 00:44