ipython/jupyter 中的 tk 问题 [英] Issues with tk in ipython/jupyter

查看:52
本文介绍了ipython/jupyter 中的 tk 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个用于从 ipython/jupyter 笔记本启动的 gui,但是在使用笔记本中的 tkinter 时遇到了问题,尤其是在让 tk gui 窗口正常关闭时.如何从 jupyter 制作/启动 tkinter gui 然后在不杀死 ipython 内核的情况下关闭它的最佳实践是什么?

I am trying to write a gui for launching from an ipython/jupyter notebook but am running into trouble using tkinter from the notebook, especially in getting the tk gui window to close gracefully. What are best practices for how to make/launch a tkinter gui from jupyter and then close it without killing the ipython kernel?

这是我第一次尝试使用 tkinter.我找到了很多关于如何使用较旧的 ipython 版本(例如 iPython 3.2)执行此操作的详细信息,但对于较新的版本(我使用的是 iPython 6.5 和 Python 3.7.1)则没有那么多.

This is my first time trying to use tkinter. I found a lot of detailed info about how to do this with older ipython versions (e.g., iPython 3.2), but not as much for more recent versions (I am using iPython 6.5 and Python 3.7.1).

这是我尝试过的示例:

%gui tk

class MyApp:

    def __init__(self, root):
        frame = tk.Frame(root)
        frame.pack()

        self.button = tk.Button(frame, text="Hello", command=self.hello_world)
        self.button.pack(side=tk.LEFT)

        self.quitbutton = tk.Button(frame, text="QUIT", fg="red", command=root.destroy)
        self.quitbutton.pack(side=tk.RIGHT)

    def hello_world(self):
        print("Hello World!")

root = tk.Tk()

app = MyApp(root)

对我来说,这运行良好,直到我尝试关闭 tkinter 窗口:按下我的退出"按钮或手动关闭窗口会导致内核被杀死或我的 mac Dock 中的残留python"应用程序除非我强制退出,否则不会消失(这也会杀死 ipython 内核).

For me, this runs fine until I try to get the tkinter window to close: either pressing my "QUIT" button or manually closing the window results in a killed kernel or a residual "python" app in my mac dock that does not go away unless I force quit it (which also kills the ipython kernel).

推荐答案

我也面临这个问题.我目前正在为此实施一种解决方法.

I am also facing the issue. I'm currently implementing a workaround for this.

由于 root.destroy() 命令不会停止 tkinter 内核的代码,所以我使用了 root.quit() 命令.如果您使用 root.quit,内核将完成代码,您可以在下一个内核中执行代码,这样,您可以在运行时让对话框加载并停留在那里接下来的行.到最后,一旦我的代码完成了它应该做的事情,我就使用 quit(0) 完全退出整个事情.

Since the root.destroy() command doesn't stop the code of the tkinter kernal, I've used the root.quit() command. If you use root.quit, the kernel will finish with the code and you can execute the code in the next kernels and in this way, you can just let the dialog box load and stay there while you run the lines that follow. By the end I just used quit(0) to quit the whole thing entirely once my code has done what it was supposed to do.

这篇关于ipython/jupyter 中的 tk 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆