0

I've read some post on stack overflow,Issues intercepting subprocess output in real time, Redirect command line results to a tkinter GUI, i know i have to use threading and queue in tkinter, but I am still can't do the same thing because I am a beginner in program,please help.

The goal: When press a button, getting the 'top' command output and realtime display in tkinter text widget

The issue: I've tried to follow the code, but still cannot get the output, but I have not idea how to make it work.

from tkinter import *
import tkinter as tk
import subprocess
from threading import Thread
from queue import Queue

window = tk.Tk()
window.title('realtime')
window.geometry('800x400')








text = tk.Text(window)
text.pack()
button = tk.Button(window, text= 'Press')
button.pack()


window.mainloop()

This is only the gui outlook, please help

Community
  • 1
  • 1
Ethan
  • 13
  • 2

1 Answers1

0

top refreshes itself now and then and I'm guessing that's the behavior you want to capture with threading and whatnot. However in this case it would be much easier to ask top to only run once, and have tkinter do the timing and refreshing:

import tkinter as tk
from sh import top

def update_text():
    text.delete(0.0, tk.END)
    text.insert(0.0, top('-b', n=1))
    window.after(1000, update_text) # call this function again in 1 second

window = tk.Tk()
window.title('realtime')
window.geometry('800x400')

text = tk.Text(window)
text.pack()
button = tk.Button(window, text= 'Press', command=update_text)
button.pack()

window.mainloop()

You may need to install sh to run top like I did, or use subprocess.check_output if you want.

text.insert(0.0, subprocess.check_output(['top', '-b', '-n 1']))
Novel
  • 13,406
  • 2
  • 25
  • 41
  • Can you help my other question please?[link](http://stackoverflow.com/questions/43388789/use-variable-in-different-class) – Ethan Apr 13 '17 at 09:43