2

I read through many of solutions of this problem already, but I still can't make this simple program work. I know it's probably really simple, but I can't find out what am I missing.

I have this simple program:

from Tkinter import *
import subprocess

def run():
    process=subprocess.Popen(some_script, shell=True, stdout=subprocess.PIPE)
    while True:
        nextline = process.stdout.readline()
        if not nextline:
            break
        output.set(nextline)
        root.update_idletasks()

root = Tk()
output = StringVar()

label1 = Label(root, textvariable=output)
label1.pack()

button1 = Button(root, text="Go", command=run)
button1.pack()

root.mainloop()

So when I click the button, some_script is executed. I want the label to periodically update with the output of the script, but it doesn't. What am I doing wrong?

Mates
  • 65
  • 1
  • 7
  • related [Python Tkinter Label redrawing every 10 seconds](https://stackoverflow.com/q/17847869/4279) – jfs Sep 26 '17 at 14:35
  • to avoid blocking GUI on `process.stdout.readline()`, you could [put it into a background thread or (on POSIX) use `createfilehandler()` to read the output asynchroniously](https://stackoverflow.com/questions/15362372/display-realtime-output-of-a-subprocess-in-a-tkinter-widget#comment24334740_15362372) – jfs Sep 26 '17 at 14:39

1 Answers1

2

I'm guessing the GUI becomes unresponsive when you run this. If so, then you're blocking Tkinter's main loop. You'll need to run the subprocess bit in a Thread and use whatever Tkinter's thread-safe methods are to update your GUI. I found this old article that sounds very similar to what you're doing: http://effbot.org/zone/tkinter-threads.htm

There's also this handy recipe: http://code.activestate.com/recipes/82965-threads-tkinter-and-asynchronous-io/

Mike Driscoll
  • 32,629
  • 8
  • 45
  • 88