Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

python - Show command prompt in tkinter window

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: I know this has been posted before, but they don't work for me :(

Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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('
')[-2]
    if command == 'exit':
        exit()
    cmd.insert('end', f'
{subprocess.getoutput(command)}')


root = Tk()

cmd = Text(root)
cmd.pack()

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

root.mainloop()

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

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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...