在 tkinter 窗口中显示命令提示符 [英] Show command prompt in tkinter window

查看:84
本文介绍了在 tkinter 窗口中显示命令提示符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何制作一个可以运行一段代码的程序,然后显示结果?因此,如果我让我的程序运行 python --version 它应该打印类似 Python 3.8.3 的内容(取决于您使用的版本),但您明白了

How do I make a program where I can run a piece of code, then show the results? So if I make my program run python --version it should print something like Python 3.8.3 (depends on what version you are on), but you get the point

PS:我知道这之前已经发布过,但它们对我不起作用:(

PS: I know this has been posted before, but they don't work for me :(

谢谢!!

推荐答案

所以这里我做了一个你可能想要的非常简单的版本(输入 python --version 来试试):

So here I made a very simple version of what You may want (type in python --version to try out):

from tkinter import Tk, Text
import subprocess


def run(event):
    command = cmd.get('1.0', 'end').split('\n')[-2]
    if command == 'exit':
        exit()
    cmd.insert('end', f'\n{subprocess.getoutput(command)}')


root = Tk()

cmd = Text(root)
cmd.pack()

cmd.bind('<Return>', run)

root.mainloop()

如果使用给定命令,subprocess.getoutput() 获取 cmd 将给出的输出

the subprocess.getoutput() gets the output the cmd would give if the given command was used

编辑(在此处移动评论):
但是有一些限制,例如运行 pause 只会使 tkinter 崩溃,并且只有在命令完成运行后才会给出输出,例如,如果您 tracert google.com 可能需要一段时间,并且在该窗口期间将无响应,直到它完成该过程然后将其全部输出(也许因为至少可以使用线程不使窗口无响应)

EDIT (moved comment here):
there are some limitations however for example running pause will just crash tkinter and the output will be given only after command has finished running for example if You tracert google.com it may take a while and during that the window will be unresponsive until it completes the process and then puts it all out (maybe for that it is possible to use threads to not make the window unresponsive at least)

编辑 (28.07.2021.):
使用 subprocess.Popen 并从那里流式传输数据可能更好

EDIT (28.07.2021.):
Probably better to use subprocess.Popen and stream data from there

这篇关于在 tkinter 窗口中显示命令提示符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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