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

如何在Python中无限期地重复命令,python,tkinter,raspberry-pi,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[

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

参考资料:

这可能不是最好的方法,但它可以工作(python 3):

从tkinter导入*
导入子流程
root=Tk()
标签=标签(根)
label.pack()
def doEvent():
全球标签
输出=子流程。检查输出('date',shell=True)
标签[“文本”]=输出
标签。之后(1000,doEvent)
doEvent()
root.mainloop()

您需要学习如何多路复用I/O。这里有三件事:子流程、子流程的I/O和用户通过TK发送的事件。请参阅:您只是一次又一次地重新分配到
输出
;您永远无法访问程序的其余部分,因此不会显示任何内容。仅供参考,由于您没有分配给
标签
,因此不需要
全局标签
语句。@Robᵩ 是的,它看起来像我自己的“脑袋里的虫子”。我想看看变量从哪里来:)