1

I have a script here that is suppose to use a command to output the temperature of a RPi.

from tkinter import *
import subprocess

win = Tk()

f1 = Frame( win )

while True:
    output = subprocess.check_output('/opt/vc/bin/vcgencmd measure_temp', shell=True)

tp = Label( f1 , text='Temperature: ' + str(output[:-1]))

f1.pack()

tp.pack()

win.mainloop()

Since I want to see the temperature change, I tried to make the command repeat itself but it breaks the script. How can I make the command repeat itself so I can have constantly updating temperature?

  • You need to learn how to multiplex I/O. You have three things going on here: a subprocess, the subprocess's I/O and event from the user through TK. – James Mills Apr 30 '15 at 03:53
  • See: [Dynamically updating Tkinter window based on serial data](http://stackoverflow.com/questions/10574821/dynamically-updating-tkinter-window-based-on-serial-data) – James Mills Apr 30 '15 at 03:58
  • You're just reassigning to `output` over and over forever; you never get to the rest of the program, so nothing ever shows up. – abarnert Apr 30 '15 at 04:09

2 Answers2

2

You can use the Tk.after() method to run your command periodically. On my PC, I don't have a temperature sensor, but I do have a time sensor. This program updates the display every 2 seconds with a new date:

from tkinter import *
import subprocess

output = subprocess.check_output('sleep 2 ; date', shell=True)

win = Tk()
f1 = Frame( win )
tp = Label( f1 , text='Date: ' + str(output[:-1]))
f1.pack()
tp.pack()

def task():
    output = subprocess.check_output('date', shell=True)
    tp.configure(text = 'Date: ' + str(output[:-1]))
    win.after(2000, task)
win.after(2000, task)

win.mainloop()

Reference: How do you run your own code alongside Tkinter's event loop?

Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

It could be not best way, but it works(python 3):

from tkinter import *
import subprocess

root = Tk()

label = Label( root)
label.pack()


def doEvent():
  global label
  output = subprocess.check_output('date', shell=True)
  label["text"] = output
  label.after(1000, doEvent)


doEvent()

root.mainloop()
Reishin
  • 1,854
  • 18
  • 21
  • FYI, since you are not assigning to `label`, you do not need the `global label` statement. – Robᵩ Apr 30 '15 at 04:40
  • @Robᵩ yes, it looks like my own "bugs in the head". I like to see from where come the variable :) – Reishin Apr 30 '15 at 05:21