如何无限期地在 Python 中重复命令 [英] How to repeat command in Python indefinitely
本文介绍了如何无限期地在 Python 中重复命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我这里有一个脚本,假设使用命令来输出 RPi 的温度.
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:
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()
因为我想看到温度变化,所以我试图让命令重复,但它破坏了脚本.如何让命令重复,以便我可以不断更新温度?
Since I want to see the temperature change, I tried to make the command repeat itself but it breaks the script. How can I make the command repeat itself so I can have constantly updating temperature?
推荐答案
您可以使用 Tk.after()
方法定期运行您的命令.在我的 PC 上,我没有温度传感器,但我有一个时间传感器.此程序每 2 秒更新一次显示的新日期:
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()
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 中重复命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文