鼠标绘图教程,python画图标注
本文主要为大家介绍一个完整的python鼠标画图的例子。有需要的朋友可以借鉴一下,希望能有所帮助。祝大家进步很大,早日升职加薪。
00-1010职位需求,友情提示,分析结果处于暂停状态,2020-02-04-codegithub更新指点。
目录
作业要求
ldw老师给了一个友好的提示(虽然感觉不错/dbq其实挺有用的)
课堂上的例子是图片显示设备(可以实现打开图像镜显示图像和保存图像操作日志的功能)。
讲猫图真的很好看。
演示结束后,差不多是这样的
友情提示
然后根据上面的例子,我们会做一个鼠标画图的gui界面(有点难
先分析一下就好。
(本来想留着圆木横着竖着翻/后来放弃了/有点难/还有.良好的.如果不能把现有图上的内容画出来,我很抱歉)
其实老师上课的时候提到过要改控件(但是我改了之后好像不对。
然后开始工作。
分析
结果呈现
悬浮状态
大声说话,命名文件路径((悄悄转义
#!/usr/bin/env python
# -*-编码: utf-8 -*-
# @时间: 2019/12/3 14:22
# @作者:陈杉
# Function :GUI编程-一个简单的画板工具
导入操作系统
导入平台
导入系统
来自PyQt5。QtCore导入*
来自PyQt5。QtGui导入*
来自PyQt5。QtWidgets导入*
类PenWidthDlg(QDialog):
def __init__(self,parent=None):
超级(PenWidthDlg,self)。__init__(父级)
WidthLabel=QLabel(宽度3360 )
self.widthSpinBox=QSpinBox()
width label . set buddy(self . width spinbox)
self . width spin box . set alignment(Qt。AlignRightQt。AlignVCenter)
self.widthSpinBox.setRange(0,50)
ok button=q button( ok )
cancel button=q button( cancel )
layout=QGridLayout()
layout.addWidget(widthLabel,0,0)
layout . add widget(self . width spin box,0,1)
layout.addWidget(okButton,1,0)
layout.addWidget(cancelButton,1,1)
self.setLayout(布局)
Self.setWindowTitle(宽度设置)
ok button . clicked . connect(self . accept)
取消按钮.单击.连接(选择
f.reject)
class myMainWindow(QMainWindow):
def __init__(self,parent=None):
super().__init__(parent)
self.setWindowTitle("draw")
self.pix=QPixmap()
self.lastPoint=QPoint()
self.endPoint=QPoint()
#初始化参数
self.initData()
#清空画布
self.initView()
#菜单栏
self.Menu = self.menuBar().addMenu("菜单")
#清空
self.ClearAction = QAction(QIcon("images/clear.png"), "清空", self)
self.ClearAction.triggered.connect(self.initView)
self.Menu.addAction(self.ClearAction)
#调画笔颜色
self.changeColor = QAction(QIcon("images/icon.png"), "颜色", self)
self.changeColor.triggered.connect(self.showColorDialog)
self.Menu.addAction(self.changeColor)
#调画笔粗细
self.changeWidth = QAction(QIcon("images/width.png"), "宽度", self)
self.changeWidth.triggered.connect(self.showWidthDialog)
self.Menu.addAction(self.changeWidth)
# #右侧停靠窗口
# logDockWidget=QDockWidget("Log",self)
# logDockWidget.setAllowedAreas(Qt.LeftDockWidgetAreaQt.RightDockWidgetArea)
# self.listWidget=QListWidget()
# logDockWidget.setWidget(self.listWidget)
# self.addDockWidget(Qt.RightDockWidgetArea,logDockWidget)
#各种动作
self.fileOpenAction = QAction(QIcon("images/fileopen.png"), "&Open", self)
self.fileOpenAction.setShortcut(QKeySequence.Open)
self.fileOpenAction.setToolTip("Open an image.")
self.fileOpenAction.setStatusTip("Open an image.")
self.fileOpenAction.triggered.connect(self.fileOpen)
self.fileSaveAction = QAction(QIcon("images/filesave.png"), "&Save", self)
self.fileSaveAction.setShortcut(QKeySequence.Save)
self.fileSaveAction.setToolTip("Save an image.")
self.fileSaveAction.setStatusTip("Save an image.")
self.fileSaveAction.triggered.connect(self.fileSaveAs)
#工具栏
fileToolbar = self.addToolBar("文件")
fileToolbar.addAction(self.fileOpenAction)
fileToolbar.addAction(self.fileSaveAction)
editToolbar = self.addToolBar("清空")
editToolbar.addAction(self.ClearAction)
colorToolbar = self.addToolBar("颜色")
colorToolbar.addAction(self.changeColor)
widthToolbar = self.addToolBar("宽度")
widthToolbar.addAction(self.changeWidth)
#状态栏
self.sizeLabel=QLabel()
self.sizeLabel.setFrameStyle(QFrame.StyledPanelQFrame.Sunken)
status=self.statusBar()
status.setSizeGripEnabled(False)
status.addPermanentWidget(self.sizeLabel)
status.showMessage("Ready",5000)
def initData(self):
self.size = QSize(1000,1040)
self.pixmap = QPixmap(self.size)
self.dirty = False
self.filename = None
self.recentFiles = []
#新建画笔
self.width = 5
self.color = QColor(0, 0, 0)
self.pen = QPen() # 实例化画笔对象
self.pen.setColor(self.color) #设置画笔颜色
self.pen = QPen(Qt.SolidLine) #实例化画笔对象.参数:画笔样式
self.pen.setWidth(self.width) #设置画笔粗细
#新建绘图工具
self.painter = QPainter(self.pixmap)
self.painter.setPen(self.pen)
#鼠标位置
self.__lastPos = QPoint(0,0)#上一次鼠标位置
self.__currentPos = QPoint(0,0)#当前的鼠标位置
self.image = QImage()
def initView(self):
#设置界面的尺寸为__size
self.Clear()
self.imageLabel = QLabel()
self.imageLabel.setPixmap(self.pixmap)
self.setCentralWidget(self.imageLabel)
def Clear(self):
#清空画板
self.pixmap.fill(Qt.white)
self.update()
self.dirty = False
def mousePressEvent(self,event):
#鼠标按下时,获取鼠标的当前位置保存为上一次位置
pointX = event.globalX()
pointY = event.globalY()
self.__currentPos = QPoint(pointX,pointY)
self.dirty = True
self.__currentPos = event.pos()
self.__lastPos = self.__currentPos
def mouseMoveEvent(self,event):
#鼠标移动时,更新当前位置,并在上一个位置和当前位置间画线
self.__currentPos = event.pos()
#pointX = event.globalX()
#pointY = event.globalY()
#self.__currentPos = QPoint(pointX,pointY)
#画线
#用begin和end抱起来,表示针对这个对象,就可以在pixmap有图的情况下继续画画
self.painter.begin(self.pixmap)
self.painter.setPen(self.pen)
self.painter.drawLine(self.__lastPos, self.__currentPos)
self.__lastPos = self.__currentPos
self.painter.end()
self.update() #更新显示
self.imageLabel.setPixmap(self.pixmap)
#调画笔颜色
def showColorDialog(self):
col = QColorDialog.getColor()
self.pen.setColor(col)
self.painter.setPen(self.pen)
def updateWidth(self):
self.pen.setWidth(self.width)
self.painter.setPen(self.pen)
def showWidthDialog(self):
dialog = PenWidthDlg(self)
dialog.widthSpinBox.setValue(self.width)
if dialog.exec_():
self.width = dialog.widthSpinBox.value()
self.updateWidth()
###########################################################
def okToContinue(self): #警告当前图像未保存
if self.dirty:
reply = QMessageBox.question(self,
"Image Changer - Unsaved Changes",
"图片已被更改,请问要保存吗?",
QMessageBox.YesQMessageBox.NoQMessageBox.Cancel)
if reply == QMessageBox.Cancel:
return False
elif reply == QMessageBox.Yes:
return self.fileSaveAs()
return True
def fileOpen(self):
if not self.okToContinue():
return
dir = (os.path.dirname(self.filename)
if self.filename is not None else ".")
formats = (["*.{}".format(format.data().decode("ascii").lower())
for format in QImageReader.supportedImageFormats()])
fname = QFileDialog.getOpenFileName(self,
"Image Changer - Choose Image", dir,
"Image files ({})".format(" ".join(formats)))
if fname:
print(fname[0])
self.loadFile(fname[0])
self.updateFileMenu()
def loadFile(self, fname=None):
if fname is None:
action = self.sender()
if isinstance(action, QAction):
fname = action.data()
if not self.okToContinue():
return
else:
return
if fname:
self.filename = None
image = QImage(fname)
if image.isNull():
message = "Failed to read {}".format(fname)
else:
self.addRecentFile(fname)
self.image = QImage()
#self.editUnMirrorAction.setChecked(True)
self.image = image
self.filename = fname
self.showImage()
self.dirty = False
self.sizeLabel.setText("{} x {}".format(
image.width(), image.height()))
message = "Loaded {}".format(os.path.basename(fname))
self.updateStatus(message)
def updateStatus(self, message):
self.statusBar().showMessage(message, 5000)
#self.listWidget.addItem(message)
if self.filename:
self.setWindowTitle("Image Changer - {}[*]".format(
os.path.basename(self.filename)))
elif not self.image.isNull():
self.setWindowTitle("Image Changer - Unnamed[*]")
else:
self.setWindowTitle("Image Changer[*]")
self.setWindowModified(self.dirty)
def updateFileMenu(self):
self.Menu.clear()
self.Menu.addAction(self.fileOpenAction)
self.Menu.addAction(self.fileSaveAction)
current = self.filename
recentFiles = []
print(self.recentFiles)
for fname in self.recentFiles:
if fname != current and QFile.exists(fname):
recentFiles.append(fname)
if recentFiles:
self.fileMenu.addSeparator()
for i, fname in enumerate(recentFiles):
action = QAction(QIcon("images/icon.png"),
"&{} {}".format(i + 1, QFileInfo(
fname).fileName()), self)
action.setData(fname)
action.triggered.connect(lambda: self.loadFile(fname))
self.fileMenu.addAction(action)
def addRecentFile(self, fname):
if fname is None:
return
if fname not in self.recentFiles:
if len(self.recentFiles) < 10:
self.recentFiles = [fname] + self.recentFiles
else:
self.recentFiles = [fname] + self.recentFiles[:8]
print(len(self.recentFiles))
def fileSaveAs(self):
savePath = QFileDialog.getSaveFileName(self, Save Your Paint, .\\, *.png)
print(savePath)
if savePath[0] == "":
print("Save cancel")
return
image = self.pixmap
print("save...")
image.save(savePath[0])
self.updateStatus("Saved as {}".format(savePath))
def showImage(self, percent=None):
if self.image.isNull():
return
self.pixmap = QPixmap.fromImage(self.image)
self.imageLabel.setPixmap(self.pixmap)
app=QApplication(sys.argv)
form=myMainWindow()
form.setMinimumSize(1000,1000)
form.show()
app.exec_()
以上就是python鼠标绘图附代码的详细内容,更多关于python鼠标绘图的资料请关注盛行IT软件开发工作室其它相关文章!
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。