我最近做了一个红绿灯程序(图形用户界面),我不知道这是错误的,我不知道如何包括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_())
这将是实现它的一个暗示。您需要定义一些函数或对象来处理循环的不同位置。此外,使用函数
self.update()
调用paintEvent
和application.processEvents()
使更改在gui中可见。您可以在执行部分使用代码,并从中生成更复杂的函数。你知道吗编辑:使用字典尝试这种方法,因为它包含的代码较少。你知道吗
尽管@f.wue的响应显然是不正确的,因为您不应该在GUI线程中使用
time.sleep()
,因为它会冻结应用程序,例如,在运行time.sleep()
时尝试调整窗口大小。你知道吗相反,您应该使用
QTimer
,正如您所说,计时器必须连接到更改颜色的函数,并调用间接调用paintEvent()
事件的update()
方法。由于希望颜色循环更改颜色,因此必须创建循环迭代器。你知道吗相关问题 更多 >
编程相关推荐