Running Tkinter with interactive ipython notebook

生来就可爱ヽ(ⅴ<●) 提交于 2020-06-17 10:45:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/61684957/running-tkinter-with-interactive-ipython-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!