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

时间:2015-04-30 03:45:29

标签: python tkinter raspberry-pi

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

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

2 个答案:

答案 0 :(得分:2)

您可以使用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()

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

答案 1 :(得分:1)

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