如何在 Python 中无限期地重复命令



我这里有一个脚本,它假设使用命令来输出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()

由于我想看到温度变化,我试图让命令重复自己,但它破坏了脚本。如何使命令重复,以便我可以不断更新温度?

可以使用

Tk.after() 方法定期运行命令。在我的电脑上,我没有温度传感器,但我有一个时间传感器。此程序每 2 秒更新一次显示,显示日期为:

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

参考:你如何在Tkinter的事件循环中运行自己的代码?

这可能不是最好的方法,但它有效(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()

最新更新