用鼠标绘制颜色连续变化的图形python
时间: 2023-07-12 16:20:12 浏览: 53
好的,以下是一个使用PyQt5的例子程序,可以通过鼠标绘制颜色连续变化的图形:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtGui import QPainter, QPen, QColor
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 设置窗口的标题和大小
self.setWindowTitle("Colorful Drawing")
self.setGeometry(100, 100, 800, 600)
# 创建 QWidget 对象,用于接收鼠标事件
self.widget = QWidget(self)
self.widget.setGeometry(0, 0, 800, 600)
self.widget.mousePressEvent = self.mousePressEvent
self.widget.mouseMoveEvent = self.mouseMoveEvent
# 初始化画笔属性
self.color = QColor(0, 0, 0)
self.penWidth = 5
# 初始化绘图状态
self.drawing = False
self.lastPoint = None
def mousePressEvent(self, event):
# 记录鼠标按下的位置
self.lastPoint = event.pos()
self.drawing = True
def mouseMoveEvent(self, event):
# 绘制线条
if self.drawing:
qp = QPainter(self.widget)
pen = QPen(self.color)
pen.setWidth(self.penWidth)
qp.setPen(pen)
qp.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
def paintEvent(self, event):
# 创建 QPainter 对象
qp = QPainter()
qp.begin(self)
# 绘制矩形框
pen = QPen(QColor(0, 0, 0))
pen.setWidth(2)
qp.setPen(pen)
qp.drawRect(0, 0, 799, 599)
# 结束 QPainter 绘图
qp.end()
def keyPressEvent(self, event):
# 处理按键事件
if event.key() == Qt.Key_C:
self.widget.repaint()
elif event.key() == Qt.Key_R:
self.color = QColor(255, 0, 0)
elif event.key() == Qt.Key_G:
self.color = QColor(0, 255, 0)
elif event.key() == Qt.Key_B:
self.color = QColor(0, 0, 255)
elif event.key() == Qt.Key_Plus:
self.penWidth += 1
elif event.key() == Qt.Key_Minus:
self.penWidth -= 1
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
```
运行程序后,将会显示一个绘图窗口。按下鼠标左键并拖动即可绘制线条,按下键盘上的 C 键可以清空画布,按下 R、G、B 键可以分别设置画笔颜色为红、绿、蓝,按下加号和减号键可以调整画笔宽度。绘制的线条颜色会随着鼠标移动的位置而连续变化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)