gpt4 book ai didi

python - 如何让一个圆每秒改变颜色?

转载 作者:行者123 更新时间:2023-12-01 08:13:31 25 4
gpt4 key购买 nike

我最近制作了一个红绿灯程序(gui),我不知道哪个是错误的,我不知道如何包含 QTimer 或任何延迟函数来改变颜色,我尝试了显示函数最终得到两个程序我真的不知道如何修复我的代码,但你能帮我吗?

import PyQt5, sys, time,os
from os import system,name
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QPoint,QTimerEvent,QTimer,Qt
from PyQt5.QtWidgets import QWidget,QApplication,QMainWindow
from PyQt5.QtGui import QPainter
class Stoplight(QMainWindow):
def __init__(self,parent = None):
QWidget.__init__(self,parent)
self.setWindowTitle("Stoplight")
self.setGeometry(500,500,250,510)
def paintEvent(self,event):
radx = 50
rady = 50
center = QPoint(125,125)
p = QPainter()
p.begin(self)
p.setBrush(Qt.white)
p.drawRect(event.rect())
p.end()

p1 = QPainter()
p1.begin(self)
p1.setBrush(Qt.red)
p1.setPen(Qt.black)
p1.drawEllipse(center,radx,rady)
p1.end()
class Stoplight1(Stoplight):
def __init__(self,parent = None):
QWidget.__init__(self,parent)
self.setWindowTitle("Stoplight")
self.setGeometry(500,500,250,510)
def paintEvent(self,event):
radx = 50
rady = 50
center = QPoint(125,125)
p = QPainter()
p.begin(self)
p.setBrush(Qt.white)
p.drawRect(event.rect())
p.end()

p1 = QPainter()
p1.begin(self)
p1.setBrush(Qt.green)
p1.setPen(Qt.black)
p1.drawEllipse(center,radx,rady)
p1.end()
if __name__ == "__main__":
application = QApplication(sys.argv)
stoplight1 = Stoplight()
stoplight2 = Stoplight1()
time.sleep(1)
stoplight1.show()
time.sleep(1)
stoplight2.show()
sys.exit(application.exec_())

最佳答案

虽然 @f.wue 的回复工作显然不正确,因为您不应该使用 time.sleep()在 GUI 线程中,因为它会卡住应用程序,例如尝试在运行 time.sleep() 时调整窗口大小。

您应该使用 QTimer正如你所说,该计时器必须连接到一个改变颜色的函数并调用 update()间接调用 paintEvent() 的方法事件。由于您希望颜色循环改变颜色,因此必须创建一个循环迭代器。

from itertools import cycle
from PyQt5 import QtCore, QtGui, QtWidgets

class TrafficLight(QtWidgets.QMainWindow):
def __init__(self,parent = None):
super(TrafficLight, self).__init__(parent)
self.setWindowTitle("TrafficLight ")
self.traffic_light_colors = cycle([
QtGui.QColor('red'),
QtGui.QColor('yellow'),
QtGui.QColor('green')
])
self._current_color = next(self.traffic_light_colors)
timer = QtCore.QTimer(
self,
interval=2000,
timeout=self.change_color
)
timer.start()
self.resize(200, 400)

@QtCore.pyqtSlot()
def change_color(self):
self._current_color = next(self.traffic_light_colors)
self.update()

def paintEvent(self, event):
p = QtGui.QPainter(self)
p.setBrush(self._current_color)
p.setPen(QtCore.Qt.black)
p.drawEllipse(self.rect().center(), 50, 50)

if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = TrafficLight()
w.show()
sys.exit(app.exec_())

关于python - 如何让一个圆每秒改变颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55088728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com