问题
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:
- I make a file, lets call it
example.pywith 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)
- 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