使用交互式ipython Notebook运行Tkinter [英] Running Tkinter with interactive ipython notebook
问题描述
我想创建一个交互式的python编码游戏,用户可以在其中输入命令到jupyter笔记本中,并在GUI上实时查看结果.这似乎在常规的python交互式shell中可以正常工作.我运行它的方式如下:
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:
- 我制作了一个文件,使用以下代码将其命名为
example.py
:
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)
- 然后在交互式python shell中执行以下操作:
>> import example
>> canvas = example.create_canvas()
>> oval = example.create_oval(canvas)
但是,当我尝试在ipython中使用它时,我没有看到GUI(我假设这是因为我不执行tkinters mainloop
函数).但是,如果我确实执行了mainloop
函数,那么我将无法再在交互式python shell中输入用户类型.
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.
所以我的问题是,如何使ipython(以便可以使用jupyter笔记本)表现得像python并显示GUI而不阻止来自控制台的用户输入?
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?
:我想出了如何使用ipython做到这一点.
我必须输入ipython --gui 'tk'
,但是如何将ipython选项传递给jupyter笔记本服务器,以便可以在笔记本中完成所有操作?
: 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?
推荐答案
好的,我知道了.
关键是要添加以下行:
%gui tk
在笔记本的开头.这样做与ipython的--gui 'tk
选项类似.
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.
这篇关于使用交互式ipython Notebook运行Tkinter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!