如何使用 idlelib.PyShell 在 tkinter 程序中嵌入解释器? [英] How to use idlelib.PyShell to embed an interpreter in a tkinter program?

查看:31
本文介绍了如何使用 idlelib.PyShell 在 tkinter 程序中嵌入解释器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的 tkinter 程序中嵌入一个交互式 Python 解释器.谁能帮我看看如何整合它?

I need to embed an interative python interpreter into my tkinter program. Could anyone help me out as to how to integrate it?

我已经查看了 main() 函数,但它对于我的需求来说很复杂,但我似乎无法在不破坏它的情况下减少它.

I have already looked at the main() function, but it's way to complex for my needs, but I can't seem to reduce it without breaking it.

推荐答案

您必须做的一些细节可能取决于您在运行 IDLE 的 Shell 后想用它做什么.我想了解更多.但是让我们从简单开始,对 pyshell.main 进行最小的更改,使其与其他代码一起运行.

Some details of what you must do may depend on what you want to do with IDLE's Shell once you have it running. I would like to know more about that. But let us start simple and make the minimum changes to pyshell.main needed to make it run with other code.

请注意,在我下面使用的 3.6 中,PyShell.py 被重命名为 pyshell.py.另请注意,此处的所有内容都相当于使用 IDLE 的私有内部结构,并且使用风险自负".

Note that in 3.6, which I use below, PyShell.py is renamed pyshell.py. Also note that everything here amounts to using IDLE's private internals and is 'use at your own risk'.

我假设您想在与 tkinter 代码相同的进程(和线程)中运行 Shell.将签名更改为

I presume you want to run Shell in the same process (and thread) as your tkinter code. Change the signature to

def main(tkroot=None):

将root创建(找到# setup root)改为

Change root creation (find # setup root) to

if not tkroot:
    root = Tk(className="Idle")
    root.withdraw()
else:
    root = tkroot

在当前的 3.6 中,在 if not tkroot 下还有几行要缩进:

In current 3.6, there are a couple more lines to be indented under if not tkroot:

    if use_subprocess and not testing:
        NoDefaultRoot()

保护主循环并销毁(最后)

Guard mainloop and destroy (at the end) with

if not tkroot:
    while flist.inversedict:  # keep IDLE running while files are open.
        root.mainloop()
    root.destroy()
# else leave mainloop and destroy to caller of main

以上为函数添加了根窗口的依赖注入".我可能会在 3.6 中添加它以使测试(其他代码"的示例)更容易.

The above adds 'dependency injection' of a root window to the function. I might add it in 3.6 to make testing (an example of 'other code') easier.

下面的 tkinter 程序现在运行,显示根窗口和空闲 shell.

The follow tkinter program now runs, displaying the both the root window and an IDLE shell.

from tkinter import *
from idlelib import pyshell

root = Tk()
Label(root, text='Root id is '+str(id(root))).pack()
root.update()
def later():
    pyshell.main(tkroot=root)
    Label(root, text='Use_subprocess = '+str(pyshell.use_subprocess)).pack()

root.after(0, later)
root.mainloop()

您应该可以随时调用 pyshell.main.

You should be able to call pyshell.main whenever you want.

这篇关于如何使用 idlelib.PyShell 在 tkinter 程序中嵌入解释器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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