• 4344阅读
  • 2回复

解决第4章例子“25行弹出式闹钟”对PyQt5+Python3兼容性的问题。 [复制链接]

上一主题 下一主题
离线wps2000
 

只看楼主 倒序阅读 楼主  发表于: 2016-10-10
原例用的是PyQt4,源码如下:

import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication(sys.argv)

try:
    due = QTime.currentTime()
    message = "Alert!"
    if len(sys.argv) < 2:
        raise ValueError
    hours, mins = sys.argv[1].split(":")
    due = QTime(int(hours), int(mins))
    if not due.isValid():
        raise ValueError
    if len(sys.argv) > 2:
        message = " ".join(sys.argv[2:])
except ValueError:
    message = "Usage: alert.pyw HH:MM [optional message]" # 24hr clock

while QTime.currentTime() < due:
    time.sleep(20) # 20 seconds

label = QLabel("<font color=red size=72><b>" + message + "</b></font>")
label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(60000, app.quit) # 1 minute
app.exec_()

============================分割线=========================================
如果用PyQt5,在原码的基础上,将from PyQt4.QtCore import * 改成from PyQt5.QtCore import *,from PyQt5.QtGui import *,程序是无法正确运行的。运行之后,没有任何反应。原因在于,QApplication 已经定位到PyQt5.QtWidgets这个模块了。所以,要加入from PyQt5.QtWidgets import *。完整的代码为:

import sys
import time
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

app = QApplication(sys.argv)

try:
    due = QTime.currentTime()
    message = "Alert!"
    if len(sys.argv) < 2:
        raise ValueError

    hours,mins = sys.argv[1].split(":")
    due = QTime(int(hours),int(mins))
    if not due.isValid():
        raise ValueError

    if len(sys.argv) > 2:
        message = " ".join(sys.argv[2:])

except ValueError:
    message = "Usage:alert.pyw HH:MM [optional message]"

while QTime.currentTime() < due:
    time.sleep(20)

label = QLabel("<font color=red size=72><b>" + message + "</b></font>")

label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(60000,app.quit)
app.exec_()
1条评分好评度+1
linote 好评度 +1 好贴 2017-04-16
离线木子心

只看该作者 1楼 发表于: 2016-11-08
第四章第一页第四段写到“但是在windows平台上,需要确保Windows用pythonw.exe解释器而不是pythonw.exe解释器来运行.pyw的文件后缀”,这两个解释器不是一样的吗?应该是排版错误吧,反复看了几遍看的我一愣一愣的

另外,改过之后的代码,在cmd下
python alert.pyw 12:00 wake      或者是
pythonw alert.pyw 12:00 wake
都可以,亲测可用
离线wps2000

只看该作者 2楼 发表于: 2017-06-23
回 木子心 的帖子
木子心:第四章第一页第四段写到“但是在windows平台上,需要确保Windows用pythonw.exe解释器而不是pythonw.exe解释器来运行.pyw的文件后缀”,这两个解释器不是一样的吗?应该是排版错误吧,反复看了几遍看的我一愣一愣的[表情]
另外,改过之后的代码,在cmd下
python alert.pyw 12:00  .. (2016-11-08 14:53) 

是的,应该是排版错误
快速回复
限100 字节
 
上一个 下一个