python编写出写字板程序的代码
时间: 2023-11-12 20:55:46 浏览: 72
写字板程序
以下是一个使用 Python 和 PyQt5 模块编写的简单写字板程序代码:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QFileDialog, QColorDialog
from PyQt5.QtGui import QIcon, QImage, QPainter, QPen
from PyQt5.QtCore import Qt, QPoint
import sys
class PaintApp(QMainWindow):
def __init__(self):
super().__init__()
self.title = "Python写字板"
self.setGeometry(100, 100, 800, 600)
self.image = QImage(self.size(), QImage.Format_RGB32)
self.image.fill(Qt.white)
self.last_point = QPoint()
self.pen = QPen(Qt.black, 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setWindowIcon(QIcon("icon.png"))
main_menu = self.menuBar()
file_menu = main_menu.addMenu("文件")
color_menu = main_menu.addMenu("颜色")
save_action = QAction(QIcon("save.png"), "保存", self)
save_action.setShortcut("Ctrl+S")
save_action.triggered.connect(self.save)
clear_action = QAction(QIcon("clear.png"), "清空", self)
clear_action.setShortcut("Ctrl+C")
clear_action.triggered.connect(self.clear)
exit_action = QAction(QIcon("exit.png"), "退出", self)
exit_action.setShortcut("Ctrl+Q")
exit_action.triggered.connect(self.close)
file_menu.addAction(save_action)
file_menu.addAction(clear_action)
file_menu.addAction(exit_action)
color_action = QAction(QIcon("color.png"), "选择颜色", self)
color_action.triggered.connect(self.color_picker)
color_menu.addAction(color_action)
self.show()
def paintEvent(self, event):
painter = QPainter(self)
painter.drawImage(self.rect(), self.image, self.image.rect())
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.last_point = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() and Qt.LeftButton:
painter = QPainter(self.image)
painter.setPen(self.pen)
painter.drawLine(self.last_point, event.pos())
self.last_point = event.pos()
self.update()
def save(self):
file_path, _ = QFileDialog.getSaveFileName(self, "保存", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*)")
if file_path == "":
return
self.image.save(file_path)
def clear(self):
self.image.fill(Qt.white)
self.update()
def color_picker(self):
color = QColorDialog.getColor()
if color.isValid():
self.pen.setColor(color)
if __name__ == '__main__':
app = QApplication(sys.argv)
paint_app = PaintApp()
sys.exit(app.exec_())
```
这个程序创建了一个基本的 PyQt5 窗口,并在其中添加了一个画布对象。当鼠标在画布上按下并拖动时,程序会在画布上创建一条黑色的线条,模拟笔的效果。程序还提供了选择颜色、保存和清空画布等功能。
阅读全文