在 tkinter 窗口中显示命令提示符

编程入门 行业动态 更新时间:2024-10-25 08:15:36
本文介绍了在 tkinter 窗口中显示命令提示符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如何制作一个可以运行一段代码的程序,然后显示结果?因此,如果我让我的程序运行 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 可能需要一段时间,并且在该窗口期间将无响应,直到它完成该过程然后将其全部输出(也许因为至少可以使用线程不使窗口无响应)

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 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 05:38:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:命令提示符   窗口中   tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!