[英]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.我想创建一个交互式 python 编码游戏,用户可以在其中将命令输入到 jupyter notebook 并在 GUI 上实时查看结果。 This seems to work fine in the regular python interactive shell.
这似乎在常规 python 交互式 shell 中工作正常。 The way I get this to run is the following:
我让它运行的方式如下:
example.py
with the following code: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)
>> 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).但是,当我尝试在 ipython 中使用它时,我没有看到 GUI(我假设这是因为我没有执行 tkinters
mainloop
函数)。 But if I do execute the mainloop
function, then I can't have the user type in an interactive python shell anymore.但是如果我确实执行了
mainloop
,那么我就不能再让用户输入交互式 python shell。
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(所以我可以使用 jupyter 笔记本)表现得像 python 并在不阻止来自控制台的用户输入的情况下显示 GUI?
[EDIT]: I figured out how to do it with ipython. [编辑]:我想出了如何用 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?我必须输入
ipython --gui 'tk'
但如何将 ipython 选项传递给 jupyter 笔记本服务器,以便我可以在笔记本中完成所有这些操作?
Okay, I figured it out.好吧,我想通了。
The key is to put the line: %gui tk
at the start of the notebook.关键是将行:
%gui tk
放在笔记本的开头。 This does something similar to the --gui 'tk
option for ipython.这与 ipython 的
--gui 'tk
选项类似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.