Skip to content Skip to sidebar Skip to footer

How To Repeat Command In Python Indefinitely

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: o

Solution 1:

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()

deftask():
    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?

Solution 2:

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

from tkinter import *
import subprocess

root = Tk()

label = Label( root)
label.pack()


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


doEvent()

root.mainloop()

Post a Comment for "How To Repeat Command In Python Indefinitely"