【发布时间】:2016-08-01 20:48:44
【问题描述】:
我正在尝试使用 PySide 开发 gui,我想知道是否有办法在 Python (QDate) 中调用函数并在特定日期和时间运行它?
例如:
#run this function in everyday at 8:00 am.
def print_something():
print "Hello"
【问题讨论】:
我正在尝试使用 PySide 开发 gui,我想知道是否有办法在 Python (QDate) 中调用函数并在特定日期和时间运行它?
例如:
#run this function in everyday at 8:00 am.
def print_something():
print "Hello"
【问题讨论】:
这是改编自 Summerfield 的 PyQt 书的第 4 章的脚本,他的 alert.py 示例。可在此处免费在线获取:
http://www.informit.com/articles/article.aspx?p=1149122
基本上你设置一个目标QDateTime,然后你可以通过将目标与currentQDateTime进行比较来触发你想要的任何可调用对象:
from PySide import QtCore, QtGui
import sys
import time
#Prepare alarm
alarmMessage = "Wake up, sleepyhead!"
year = 2016
month = 4
day = 23
hour = 12
minute = 40
alarmDateTime = QtCore.QDateTime(int(year), int(month), int(day), int(hour), int(minute), int(0))
#Wait for alarm to trigger at appropriate time (check every 5 seconds)
while QtCore.QDateTime.currentDateTime() < alarmDateTime:
time.sleep(5)
#Once alarm is triggered, create and show QLabel, and then exit application
qtApp = QtGui.QApplication(sys.argv)
label = QtGui.QLabel(alarmMessage)
label.setStyleSheet("QLabel { color: rgb(255, 0, 0); font-weight: bold; font-size: 25px; \
background-color: rgb(0,0,0); border: 5px solid rgba(0 , 255, 0, 200)}")
label.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.WindowStaysOnTopHint)
label.show()
waitTime = 10000 #in milliseconds
QtCore.QTimer.singleShot(waitTime, qtApp.quit)
sys.exit(qtApp.exec_())
这个有一个 QLabel 在您想要的日期和时间弹出,但这是任意的。你可以让它做任何你想做的事情。如果您希望它每天在同一时间运行,则必须对其进行适当的修改,但这应该足以让您开始使用QDateTime 来触发事件。
请注意,如果您在 Windows 中工作并且想在后台运行它,并且屏幕上不显示命令窗口,请按照此处的建议进行操作:
How can I hide the console window in a PyQt app running on Windows?
即,以.pyw 扩展名保存程序并确保它以pythonw.exe 运行,而不是python.exe。
【讨论】: