代码如下:
alert.py
import sys
import time
from PyQt5.QtCore import (QTime, QTimer, Qt)
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]" # 24hr clock
while QTime.currentTime() < due:
time.sleep(20) # 20 seconds
label = QLabel("<font color=red size=72><b>{0}</b></font>"
.format(message))
label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(60000, app.quit) # 1 minute
app.exec_()
用法 比如现在是 14:50 那么:
alert.py 14:00 hello_world
calculate.py
import sys
from math import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.browser = QTextBrowser()
self.lineedit = QLineEdit("Type an expression and press Enter")
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.lineedit.returnPressed.connect(self.updateUi)
self.setWindowTitle("Calculate")
def updateUi(self):
try:
text = str(self.lineedit.text())
self.browser.append("{0} = <b>{1}</b>".format(text,
eval(text)))
except:
self.browser.append("<font color=red>{0} is invalid!</font>"
.format(text))
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
界面:
code:
import sys
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
# 日期
date = '2020-5-12'
date = "Exchange Rates Date: " + date
#date = self.getdata()
self.rates = {}
self.rates['Australia'] = 5.2
self.rates['Janess'] = 3.3
self.rates['apple_coin'] = 6.6
rates = sorted(self.rates.keys())
dateLabel = QLabel(date)
self.fromComboBox = QComboBox()
self.fromComboBox.addItems(rates)
self.fromSpinBox = QDoubleSpinBox()
self.fromSpinBox.setRange(0.01, 10000000.00)
self.fromSpinBox.setValue(1.00)
self.toComboBox = QComboBox()
self.toComboBox.addItems(rates)
self.toLabel = QLabel("1.00")
grid = QGridLayout()
grid.addWidget(dateLabel, 0, 0)
grid.addWidget(self.fromComboBox, 1, 0)
grid.addWidget(self.fromSpinBox, 1, 1)
grid.addWidget(self.toComboBox, 2, 0)
grid.addWidget(self.toLabel, 2, 1)
self.setLayout(grid)
self.fromComboBox.currentIndexChanged.connect(self.updateUi)
self.toComboBox.currentIndexChanged.connect(self.updateUi)
self.fromSpinBox.valueChanged.connect(self.updateUi)
self.setWindowTitle("Currency")
self.resize(300, 300)
def updateUi(self):
to = str(self.toComboBox.currentText())
from_ = str(self.fromComboBox.currentText())
amount = ((self.rates[from_] / self.rates[to]) *
self.fromSpinBox.value())
self.toLabel.setText("{0:.2f}".format(amount))
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
connections.py
import functools
import sys
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
button1 = QPushButton("One")
button2 = QPushButton("Two")
button3 = QPushButton("Three")
button4 = QPushButton("Four")
button5 = QPushButton("Five")
self.label = QLabel("Click a button...")
layout = QHBoxLayout()
layout.addWidget(button1)
layout.addWidget(button2)
layout.addWidget(button3)
layout.addWidget(button4)
layout.addWidget(button5)
layout.addStretch()
layout.addWidget(self.label)
self.setLayout(layout)
button1.clicked.connect(self.one)
self.button2callback = functools.partial(self.anyButton, "Two")
button2.clicked.connect(self.button2callback)
self.button3callback = lambda who="Three": self.anyButton(who)
button3.clicked.connect(self.button3callback)
button4.clicked.connect(self.clicked)
button5.clicked.connect(self.clicked)
self.setWindowTitle("Connections")
def one(self):
self.label.setText("You clicked button 'One'")
def anyButton(self, who):
self.label.setText("You clicked button '{0}'".format(who))
def clicked(self):
button = self.sender()
if button is None or not isinstance(button, QPushButton):
return
self.label.setText("You clicked button '{0}'".format(
button.text()))
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
python alert_extra.py 14:00 hello_world
alert_extra.py
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import time
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
font = QFont("Helvetica", 36, QFont.Bold)
fm = QFontMetrics(font)
pixmap = QPixmap(fm.width(message) + 5, fm.height() + 5)
pixmap.fill(Qt.white)
painter = QPainter(pixmap)
document = QTextDocument()
document.setDefaultFont(font)
document.setHtml("<font color=red>{0}</font>".format(message))
document.drawContents(painter)
painter.end()
label = QLabel()
label.setPixmap(pixmap)
label.setMask(pixmap.createMaskFromColor(Qt.white))
label.setWindowFlags(Qt.SplashScreen|Qt.FramelessWindowHint)
label.show()
QTimer.singleShot(60000, app.quit) # 1 minute
app.exec_()
interest.py
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import time
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
principalLabel = QLabel("Principal:")
self.principalSpinBox = QDoubleSpinBox()
self.principalSpinBox.setRange(1, 1000000000)
self.principalSpinBox.setValue(1000)
self.principalSpinBox.setPrefix("$ ")
rateLabel = QLabel("Rate:")
self.rateSpinBox = QDoubleSpinBox()
self.rateSpinBox.setRange(1, 100)
self.rateSpinBox.setValue(5)
self.rateSpinBox.setSuffix(" %")
yearsLabel = QLabel("Years:")
self.yearsComboBox = QComboBox()
self.yearsComboBox.addItem("1 year")
self.yearsComboBox.addItems(["{0} years".format(x)
for x in range(2, 26)])
amountLabel = QLabel("Amount")
self.amountLabel = QLabel()
grid = QGridLayout()
grid.addWidget(principalLabel, 0, 0)
grid.addWidget(self.principalSpinBox, 0, 1)
grid.addWidget(rateLabel, 1, 0)
grid.addWidget(self.rateSpinBox, 1, 1)
grid.addWidget(yearsLabel, 2, 0)
grid.addWidget(self.yearsComboBox, 2, 1)
grid.addWidget(amountLabel, 3, 0)
grid.addWidget(self.amountLabel, 3, 1)
self.setLayout(grid)
self.principalSpinBox.valueChanged.connect(self.updateUi)
self.rateSpinBox.valueChanged.connect(self.updateUi)
self.yearsComboBox.currentIndexChanged.connect(self.updateUi)
self.setWindowTitle("Interest")
self.updateUi()
def updateUi(self):
"""Calculates compound interest"""
principal = self.principalSpinBox.value()
rate = self.rateSpinBox.value()
years = self.yearsComboBox.currentIndex() + 1
amount = principal * ((1 + (rate / 100.0)) ** years)
self.amountLabel.setText("$ {0:.2f}".format(amount))
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
python signals.py 3
signals.py
代码:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import time
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
dial = QDial()
dial.setNotchesVisible(True)
spinbox = QSpinBox()
layout = QHBoxLayout()
layout.addWidget(dial)
layout.addWidget(spinbox)
self.setLayout(layout)
dial.valueChanged.connect(spinbox.setValue)
spinbox.valueChanged.connect(dial.setValue)
self.setWindowTitle("Signals and Slots")
class Form2(QDialog):
def __init__(self, parent=None):
super(Form2, self).__init__(parent)
dial = QDial()
dial.setNotchesVisible(True)
spinbox = QSpinBox()
layout = QHBoxLayout()
layout.addWidget(dial)
layout.addWidget(spinbox)
self.setLayout(layout)
dial.valueChanged.connect(spinbox.setValue)
spinbox.valueChanged.connect(dial.setValue)
# self.connect(dial, SIGNAL("valueChanged(int)"),
# spinbox, SLOT("setValue(int)"))
# self.connect(spinbox, SIGNAL("valueChanged(int)"),
# dial, SLOT("setValue(int)"))
self.setWindowTitle("Signals and Slots")
class ZeroSpinBox(QSpinBox):
zeros = 0
atzero = pyqtSignal(int)
def __init__(self, parent=None):
super(ZeroSpinBox, self).__init__(parent)
self.valueChanged.connect(self.checkzero)
def checkzero(self):
if self.value() == 0:
self.zeros += 1
self.atzero.emit(self.zeros)
class Form3(QDialog):
def __init__(self, parent=None):
super(Form3, self).__init__(parent)
dial = QDial()
dial.setNotchesVisible(True)
zerospinbox = ZeroSpinBox()
layout = QHBoxLayout()
layout.addWidget(dial)
layout.addWidget(zerospinbox)
self.setLayout(layout)
dial.valueChanged.connect(zerospinbox.setValue)
zerospinbox.valueChanged.connect(dial.setValue)
zerospinbox.atzero.connect(self.announce)
# self.connect(dial, SIGNAL("valueChanged(int)"),
# zerospinbox, SLOT("setValue(int)"))
# self.connect(zerospinbox, SIGNAL("valueChanged(int)"),
# dial, SLOT("setValue(int)"))
# self.connect(zerospinbox, SIGNAL("atzero"), self.announce)
self.setWindowTitle("Signals and Slots")
def announce(self, zeros):
print("ZeroSpinBox has been at zero {0} times".format(zeros))
class Form4(QDialog):
def __init__(self, parent=None):
super(Form4, self).__init__(parent)
lineedit = QLineEdit()
layout = QHBoxLayout()
layout.addWidget(lineedit)
self.setLayout(layout)
lineedit.textChanged.connect(self.consoleEcho)
# self.connect(lineedit, SIGNAL("textChanged(QString)"),
# self.consoleEcho)
self.setWindowTitle("Signals and Slots")
def consoleEcho(self, text):
print(str(text))
class TaxRate(QObject):
rateChanged = pyqtSignal(float)
def __init__(self):
super(TaxRate, self).__init__()
self.__rate = 17.5
def rate(self):
return self.__rate
def setRate(self, rate):
if rate != self.__rate:
self.__rate = rate
self.rateChanged.emit(self.__rate)
#self.emit(SIGNAL("rateChanged"), self.__rate)
def rateChanged(value):
print("TaxRate changed to {0:.2f}%".format(value))
app = QApplication(sys.argv)
form = None
if len(sys.argv) == 1 or sys.argv[1] == "1":
form = Form()
elif sys.argv[1] == "2":
form = Form2()
elif sys.argv[1] == "3":
form = Form3()
elif sys.argv[1] == "4":
form = Form4()
if form is not None:
form.show()
app.exec_()
else: # if sys.argv[1] == "5"
vat = TaxRate()
vat.rateChanged.connect(rateChanged)
#vat.connect(vat, SIGNAL("rateChanged"), rateChanged)
vat.setRate(17.5) # No change will occur (new rate is the same)
vat.setRate(8.5) # A change will occur (new rate is different)
实例: