Issues with tk in ipython/jupyter

Viewed 1136

I am trying to write a gui for launching from an ipython/jupyter notebook but am running into trouble using tkinter from the notebook, especially in getting the tk gui window to close gracefully. What are best practices for how to make/launch a tkinter gui from jupyter and then close it without killing the ipython kernel?

This is my first time trying to use tkinter. I found a lot of detailed info about how to do this with older ipython versions (e.g., iPython 3.2), but not as much for more recent versions (I am using iPython 6.5 and Python 3.7.1).

Here is an example I have tried:

%gui tk

class MyApp:

    def __init__(self, root):
        frame = tk.Frame(root)
        frame.pack()

        self.button = tk.Button(frame, text="Hello", command=self.hello_world)
        self.button.pack(side=tk.LEFT)

        self.quitbutton = tk.Button(frame, text="QUIT", fg="red", command=root.destroy)
        self.quitbutton.pack(side=tk.RIGHT)

    def hello_world(self):
        print("Hello World!")

root = tk.Tk()

app = MyApp(root)

For me, this runs fine until I try to get the tkinter window to close: either pressing my "QUIT" button or manually closing the window results in a killed kernel or a residual "python" app in my mac dock that does not go away unless I force quit it (which also kills the ipython kernel).

1 Answers

I am also facing the issue. I'm currently implementing a workaround for this.

Since the root.destroy() command doesn't stop the code of the tkinter kernal, I've used the root.quit() command. If you use root.quit, the kernel will finish with the code and you can execute the code in the next kernels and in this way, you can just let the dialog box load and stay there while you run the lines that follow. By the end I just used quit(0) to quit the whole thing entirely once my code has done what it was supposed to do.

Related