【问题标题】:How to use idlelib.PyShell to embed an interpreter in a tkinter program?如何使用 idlelib.PyShell 在 tkinter 程序中嵌入解释器?
【发布时间】:2016-08-16 14:25:05
【问题描述】:

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

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

【问题讨论】:

  • 其他人问过关于在 tkinter 程序中添加控制台的问题,但我不记得有人特别建议和询问过使用 IDLE 的 Shell。
  • @TerryJanReedy 我更喜欢控制台,但我还没有收到我之前关于这个问题的答案。如果您可以查看问题here,我的情况将得到进一步解释。不过感谢您的回答,这将是一个很好的临时解决方案。
  • 我希望你觉得它有用。我很确定我会的,虽然我是在写完之后才意识到这一点的 ;-)。

标签: python shell python-3.x tkinter python-idle


【解决方案1】:

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

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

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

def main(tkroot=None):

将根创建(查找# setup root)更改为

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

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

    if use_subprocess and not testing:
        NoDefaultRoot()

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

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 中添加它以使测试(“其他代码”的示例)更容易。

follow tkinter 程序现在运行,同时显示根窗口和 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。

【讨论】:

    猜你喜欢
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多