Search code examples
pythontkintersubprocessraspbian

Make tkinter label refresh at set time intervals without input


I've been trying for the past couple of hours to find a way to refresh a label with information without having to input anything myself.

The program I am trying to write is taking the CPU temp from the Raspberry Pi and displaying it in a window. I need to make that temp input to update every 5 seconds or so, but all attempts to do so have failed. I tried while loops and found that they do not work inside tkinter, and I can't think how to refresh something constantly without input without one. I am quite new to Python so I'm sure there is a way and I just haven't come across it yet. Similar questions on here don't quite lead to an answer that applies for me.

Here is my bit of code right now:

import subprocess
from tkinter import *

root = Tk()
root.title('CPU Temp')

cpuLab = Label(root, text = 'CPU Temp:',
               font =('Nimbus Mono L',14,),
               bg = 'black', fg = 'green').grid(row = 0, column = 0)

cpuTemp = subprocess.check_output(['/opt/vc/bin/vcgencmd', 'measure_temp'])

cpuVar = StringVar()
cpuDisplay = Label(root, textvariable = cpuVar,
                   font =('Nimbus Mono L',14),
                   bg = 'black', fg = 'green').grid(row = 0, column = 1)
cpuVar.set(cpuTemp[5:11])

root.mainloop()

This works perfectly for showing the temperature, it just has to be rerun in order to refresh.


Solution

  • Tkinter root windows have a method called after which can be used to schedule a function to be called after a given period of time. So call that function itself like (you will have to create a class first):

    def update_label(self):
        self.label.configure(cpuTemp)
        self.root.after(1000, self.update_label)
    

    This will then reload your label every second.

    This may help you: Creating a Timer with tkinter