Reputation: 97
I'm using Tkinter (Tk version 8.4) to create a GUI which allows a user to build a text "input" file. This text file is readable by another program, which makes calculations and then spits out an output file. I have created a menu option (using the OptionMenu widget) to run the calculation program from my GUI by clicking a "run" option. However, to make sure that the calculations have been made correctly and that the program ran correctly, you need to keep an eye on the terminal. Since the point of this GUI is to make text file building and running the calculations easier, it would be useful to display the terminal's output in a textbox or a frame within my Tkinter GUI.
I've googled and googled and googled but I can't seem to find a good, general answer to this problem. All I'd like to do is display the terminal within my GUI. How do I do this (I assume it would be only a few lines of code)?
Thanks in advance!
Upvotes: 1
Views: 6923
Reputation: 386
Hmm, I'm definitely not an expert but let me give it a shot.
Something you could do is to redirect all your terminal output to a file, say calculation.py <userinput> >> text.txt
or have that in your calculation code i.e.:
while calculation: # <- your function
with open('text.txt', 'w') as f: # <- open a text file for ouput
f.write(<calculation output>) # <- keep writing the output
or if your program is not python than os.system('<terminal command i.e. "echo foo">')
and use the first method to direct the ouput to a file.
After doing so, in your tkinter code:
def cmdOutput():
output = os.system('cat text.txt') # <- replace "cat" with "type" if windows.
return output.split("\n")[-1] # <- return the last item in the list.
while cmdOutput() == "<calculating...>": # <- or something like that.
tkinterUpdateMethodDeclaredSomewhere(cmdOutput())
else:
tkinterUpdateMethodFinalAnswer(cmdOutput())
Though I'm sure there's a better way to do this, this is one way...
you could also write a command to delete the file at the end of cmdOutput
, or read from it and paste the necessary bits to a log file or something...
I hope this helps.
Upvotes: 0
Reputation: 385980
You can't exactly show the terminal in your program, but I don't think that's really what you want anyway. It sounds like you just want to display the output of the command in your GUI.
How are you running the calculation? Are you using popen? If so, you can grab the output of the program and insert it into the text widget with something like this:
p = sub.Popen('./script',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
self.text.insert("end", output)
It gets a little more complicated if you're using threads or multiprocessing, but the concept is the same: run your program in a way that lets you capture the output, then insert the output in the text widget when it's done running.
Upvotes: 1