python鼠標繪圖附代碼
github指路
作業要求
友情提示
ldw老師給の友情提示(雖然感覺也還好/dbq其實還挺有用的)
課上講的例子是圖片展示器(能夠實現打開圖片+鏡像顯示圖片+保存圖片+操作日志的功能)
講真那啥貓咪圖片還挺好看
演示之後差不多是這樣👇
分析
然後按照上面這個樣例我們要做一個鼠標繪圖的gui界面(這就有點難度瞭
先分析一下就是👇
(我本來是想保留日志和水平翻轉垂直翻轉這種操作的/後來放棄瞭/有點難/而且……那啥……我做不到在現有的圖上繪制內容就很抱歉)
老師上課其實有提到說那啥控件要改(但是我改完之後貌似不對
然後開始幹活
結果呈現
懸浮狀態
2020/02/04 更新code
大聲說話,文件路徑&命名(((小聲逃走
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/12/3 14:22 # @Author : Chen Shan # Function :GUI programming - a naive Sketchpad tool import os import platform import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class PenWidthDlg(QDialog): def __init__(self, parent=None): super(PenWidthDlg, self).__init__(parent) widthLabel = QLabel("寬度:") self.widthSpinBox = QSpinBox() widthLabel.setBuddy(self.widthSpinBox) self.widthSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter) self.widthSpinBox.setRange(0, 50) okButton = QPushButton("ok") cancelButton = QPushButton("cancle") layout = QGridLayout() layout.addWidget(widthLabel,0,0) layout.addWidget(self.widthSpinBox,0,1) layout.addWidget(okButton,1,0) layout.addWidget(cancelButton,1,1) self.setLayout(layout) self.setWindowTitle("寬度設置") okButton.clicked.connect(self.accept) cancelButton.clicked.connect(self.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.LeftDockWidgetArea|Qt.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.StyledPanel|QFrame.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.Yes|QMessageBox.No|QMessageBox.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鼠標繪圖的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- 用Python制作一個可以聊天的皮卡丘版桌面寵物
- C/C++ Qt ToolBar菜單組件的具體使用
- PyQt QMainWindow的使用示例
- Qt數據庫應用之實現圖片轉pdf
- Python中利用pyqt5制作指針鐘表顯示實時時間(指針時鐘)