简体   繁体   中英

Running Tkinter with interactive ipython notebook

I want to create an interactive python coding game, where users can enter commands into a jupyter notebook and see the result on a GUI in real time. This seems to work fine in the regular python interactive shell. The way I get this to run is the following:

  1. I make a file, lets call it example.py with the following code:
import tkinter as tk


def create_canvas():
    root = tk.Tk()
    root.resizable(False, False)
    root.title("Karel")
    frame = tk.Frame(root)
    frame.pack()
    canvas = tk.Canvas(frame, bg="white", width=500, 
        height=500)
    canvas.pack()
    return canvas


def create_oval(canvas):
    return canvas.create_oval(150, 150, 155, 155, fill='#000')



def move(canvas, oval):
    canvas.move(oval, 0, -50)
  1. Then in the interactive python shell I do the following:
>> import example
>> canvas = example.create_canvas()
>> oval = example.create_oval(canvas)

However, when I try to get this working in ipython, I don't see a GUI (I'm assuming this is because I don't execute tkinters mainloop function). But if I do execute the mainloop function, then I can't have the user type in an interactive python shell anymore.

So my question, is how do I get ipython (so I can use jupyter notebooks) to behave like python and display the GUI without blocking user input from the console?

[EDIT]: I figured out how to do it with ipython. I have to type ipython --gui 'tk' but how do I pass ipython options to a jupyter notebook server so that I can do this all in a notebook?

Okay, I figured it out.

The key is to put the line: %gui tk at the start of the notebook. This does something similar to the --gui 'tk option for ipython.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM