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

How to repeat command in Python indefinitely

我这里有一个脚本,假设使用命令输出树莓派的温度。

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

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

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