Commit 60a005fc authored by Wichit Sombat's avatar Wichit Sombat

latest download from google team drive

parent 26b1f239
csubupromote@gmail.com
123456789Az
\ No newline at end of file
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Python for Computer Science\n",
"> wichit2s"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Programming Paradigms \n",
"\n",
"| Paradigm | Description | Languages |\n",
"|:----------------|:---------------------------------------|:------------------------------------------------------|\n",
"| Imperative | statements change state directly | C, C++, Java, PHP, **Python**, Ruby |\n",
"| Structured | imperative + logical structure | C, C++, Java, **Python** |\n",
"| Procedural | structure + modular programming | C, C++, Lisp, PHP, **Python** |\n",
"| Functional | computation as math functions | C++, Clojure, JavaScript, Lisp, **Python**, Ruby, Scala |\n",
"| Event-Driven | control flow by events | JavaScript, ActionScript, Visual Basic, Elm |\n",
"| Object-Oriented | data as object control through methods | C++, C#, Java, JavaScript, PHP, **Python**, Ruby, Scala |\n",
"| Declarative | program logic (fourth-gen) | SQL, regex, CSS, Prolog |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Textbook: PPICS\n",
"![screenshot](http://mcsp.wartburg.edu/zelle/python/ppics3/cover_small.png)\n",
"> [An Introduction to Computer Science 2nd Edition - John M. Zelle, Ph.D.](http://www.leetupload.com/database/Misc/Papers/Python%20programming%20-%20An%20introduction%20to%20computer%20science%202002.pdf)\n",
"\n",
"> [Slides](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Chapters\n",
"\n",
"| First Half | Second Half |\n",
"|:-------------------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------|\n",
"| 1. [Computers and Programs](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter01.pptx) | 7. [Control Structure 1](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter07.pptx) |\n",
"| 2. [Writing Simple Programs](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter02.pptx) | 8. [Control Structure 2](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter08.pptx) |\n",
"| 3. [Computing Numbers](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter03.pptx) | 9. [Simulation and Design](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter09.pptx) |\n",
"| 4. [Computing Strings](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter04.pptx) | 10. [Defining Classes](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter10.pptx) |\n",
"| 5. [Object and Graphics](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter05.pptx) | 11. [Data Collections](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter11.pptx) |\n",
"| 6. [Defining Functions](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter06.pptx) | 12. [Object-Oriented Design](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter12.pptx) |\n",
"| | 13. [Algoirhtm Analysis and Design](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter13.pptx) |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 1. Computers and Programs [Lecture](./01 Computers and Programs.ipynb) [Lab](./01 Computers and Programs Lab.ipynb)\n",
"\n",
"| Lectures | Laboratory |\n",
"|:----------------------------|:------------------------|\n",
"| 1. The Universal Machine | 1. Anaconda Installation |\n",
"| 2. Program Power | 2. Python Shell |\n",
"| 3. What is Computer Science? | 3. IPython Shell |\n",
"| 4. Hardware Basics | 4. Jupyter Notebook |\n",
"| 5. Programming Languages | |\n",
"| 6. The Magic of Python | |\n",
"| 7. Inside a Python Program | |\n",
"| 8. Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 2. Writing Simple Programs [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter02.pptx) [Lab](02 Writing Simple Programs Lab.ipynb)\n",
"| Lectures | Laboratory |\n",
"|:--------------------------------------------------------------------------|:------------|\n",
"| 1. The Software Development Process | |\n",
"| * **Example Program**: Temperature Converter | |\n",
"| 2. Elements or Programs: Names, Expressions | |\n",
"| 3. Output Statement | |\n",
"| 4. Assignment Statements: Simple, Assigning Input, Simultaneous Assignment | |\n",
"| 5. Definite Loops | |\n",
"| * **Example Program**: Future Value | |\n",
"| 6. Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 3. Computing with Numbers [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter03.pptx) [Lab](03 Computing with Numbers Lab.ipynb)\n",
"| Lectures | Laboratory |\n",
"|:------------------------------------|:-----------|\n",
"| * Numeric Data Types | |\n",
"| * Using The Math Library | |\n",
"| * Accumulating Results: Factorial | |\n",
"| * The Limits of Int | |\n",
"| * Handling Large Numbers: Long Ints | |\n",
"| * Type Conversions | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# 4. Computing with Strings [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter04.pptx) [Lab](04 Computing with Strings Lab.ipynb)\n",
"| Lectures | Laboratory |\n",
"|:--------------------------------|:-----------|\n",
"| * The String Data Type | |\n",
"| * Simple String Processing | |\n",
"| * Strings and Secret Codes | |\n",
"| * Output as String Manipulation | |\n",
"| * File Processing | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## 5. Objects and Graphics [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter05.pptx) [Lab](05 Objects and Graphics Lab.ipynb)\n",
"\n",
"| Lectures | Laboratory |\n",
"|:----------------------------|:-----------|\n",
"| * The Object of Objects | |\n",
"| * Graphics Programming | |\n",
"| * Using Graphical Objects | |\n",
"| * Graphing Future Value | |\n",
"| * Choosing Coordinates | |\n",
"| * Interactive Graphics | |\n",
"| * Graphics Module Reference | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 6. Defining Functions [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter06.pptx) [Lab](06 Defining Functions Lab.ipynb)\n",
"| Lectures | Laboratory |\n",
"|:---------------------------------------------|:-----------|\n",
"| * The Function of Functions | |\n",
"| * Functions, Informally | |\n",
"| * Future Value with a Function | |\n",
"| * Functions and Parameters: The Gory Details | |\n",
"| * Functions that Return Values | |\n",
"| * Functions and Program Structure | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 7. Control Structures, Part 1 [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter07.pptx) [Lab](07 Control Structures Part 1 Lab.ipynb)\n",
"| Lectures | Laboratory |\n",
"|:-------------------------------------|------------|\n",
"| * Simple Decisions | |\n",
"| * Two-Way Decisions | |\n",
"| * Multi-Way Decisions | |\n",
"| * Exception Handling | |\n",
"| * **Study in Design**: Max of Three | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 8. Control Structure, Part 2 [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter08.pptx) [Lab](08 Control Structures Part 2 Lab.ipynb)\n",
"| Lectures | Laboratory |\n",
"|:--------------------------------------------------------------------------------------------|------------|\n",
"| * For Loops: A Quick Review | |\n",
"| * Indefinite Loops | |\n",
"| * Common Loop Patterns: Interactive, Sentinel, File, Nested | |\n",
"| * Computing with Booleans: Operators, Algebra | |\n",
"| * Other Common Structures: Post-Test Loop, Loop and a Half, Boolean Expression as Decisions | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 9. Simulation and Design [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter09.pptx)\n",
"| Lectures | Laboratory |\n",
"|:-------------------------------------------------------------------------------------------------------|------------|\n",
"| * Simulating Racquetball: problem, specification | |\n",
"| * Random Numbers | |\n",
"| * Top-Down Design: Top-Level, Separation of Concerns, Second-Level, Third-Level, Finishing Up, Summary | |\n",
"| * Bottom-Up Implementation: Unit Testing, Simulation Results | |\n",
"| * Other Design Techniques: Prototyping and Spiral Development, The Art of Design | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 10. Defining Classes [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter10.pptx)\n",
"| Lectures | Laboratory |\n",
"|:------------------------------------------------------------------------------|------------|\n",
"| * Quick Review of Objects | |\n",
"| * Example Program: Cannonball, program specification, designing, modularizing | |\n",
"| * Defining New Classes | |\n",
"| * Object and Encapsulation: Encapsulating useful abstractions, Modules | |\n",
"| * Example Program: | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 11. Data Collections [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter11.pptx) [Lab](11 Data Collections Lab.ipynb)\n",
"| Lectures | Laboratory |\n",
"|:----------------------------------------------------|------------|\n",
"| * Example Problem: Simple Statistics | |\n",
"| * Applying Lists: sequences, vs. string, operations | |\n",
"| * Statistics with Lists | |\n",
"| * Combining Lists and Classes | |\n",
"| * Case Study: Python Calculator | |\n",
"| * Non-Sequential Collections: Dictionary | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 12. Object-Oriented Design [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter12.pptx)\n",
"| Lectures | Laboratory |\n",
"|:--------------------------------------------------------|------------|\n",
"| * The Process of OOD | |\n",
"| * Case Study: Racquetball Simulation | |\n",
"| * Case Study: Dice Poker | |\n",
"| * OO Concepts: Encapsulation, Polymorphism, Inheritance | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 13. Algorithm Analysis and Design [pptx](http://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter13.pptx)\n",
"| Lectures | Laboratory |\n",
"|:--------------------------------------------------------------------|------------|\n",
"| * Searching: Linear, Binary, Comparison | |\n",
"| * Recursive Problem-Solving: definition, recursive function, search | |\n",
"| * Sorting Algorithms: Selection, Merge, Comparison | |\n",
"| * Hard Problems: Towers of Hanoi, The Halting Problem | |\n",
"| * Exercises | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### keywords\n",
"\n",
"| Control | Class/Scope | Exception | Constants | Logic |\n",
"|:--------------:|:-----------:|:---------:|:------------:|:-----:|\n",
"| `if,elif,else` | `class` | `try` | `True,False` | `and` |\n",
"| `while` | `import` | `except` | `None` | `or` |\n",
"| `for` | `global` | `finally` | | `in` |\n",
"| `yield` | `nonlocal` | `assert` | | `is` |\n",
"| `continue` | `lambda` | `raise` | | `as` |\n",
"| `break` | | | | |\n",
"| `del` | | | | |"
]
}
],
"metadata": {
"celltoolbar": "Slideshow",
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
from PyQt5.QtCore import QDir, QFile, QPoint, QRect, QSize, Qt
from PyQt5.QtGui import QImage, QImageWriter, QPainter, QPen, qRgb, QPixmap
from PyQt5.QtWidgets import (QAction, QApplication, QColorDialog, QFileDialog,
QInputDialog, QMainWindow, QMenu, QMessageBox, QWidget)
class Board(QWidget):
def __init__(self,parent=None):
super(Board,self).__init__(parent)
self.setAttribute(Qt.WA_StaticContents)
self.penWidth = 50
self.writing = False
self.penColor = Qt.black
self.image = QImage()
self.lastPoint = QPoint()
self.setFixedSize(512,512)
def saveImage(self,label):
import os
visibleImage = self.image
self.resizeImage(visibleImage,self.size())
if QDir('Image').exists() == False:
QDir().mkdir('Image')
label = 'Image/'+label
if QDir(label).exists() == False:
QDir().mkdir(label)
cnt = 0
maxf = 0
for file in os.listdir(label):
if file.endswith('.bmp'):
cnt += 1
tmpN = int(file[:-4:])
maxf = max(maxf,tmpN)
visibleImage.save('tmp.bmp')
pixmap = QPixmap('tmp.bmp').scaled(8,8)
pixmap.save(label+'/'+str(max(cnt,maxf)+1)+'.bmp')
QFile.remove('tmp.bmp')
def paintEvent(self, event):
painter = QPainter(self)
dirtyRect = event.rect()
painter.drawImage(dirtyRect, self.image, dirtyRect)
def clearImage(self):
self.image.fill(qRgb(255,255,255))
self.update()
def mousePressEvent(self,event):
if event.button() == Qt.LeftButton:
self.lastPoint = event.pos()
self.writing = True
def mouseMoveEvent(self,event):
if (event.buttons() & Qt.LeftButton) and self.writing:
self.drawLineTo(event.pos())
def mouseReleaseEvent(self,event):
if event.button() == Qt.LeftButton and self.writing:
self.drawLineTo(event.pos())
self.writing = False
def resizeEvent(self,event):
self.resizeImage(self.image,self.size())
self.update()
super(Board,self).resizeEvent(event)
def drawLineTo(self, endPoint):
painter = QPainter(self.image)
painter.setPen(QPen(self.penColor, self.penWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, endPoint)
self.writing = True
rad = self.penWidth/2 + 2
self.update(QRect(self.lastPoint, endPoint).normalized().adjusted(-rad, -rad, +rad, +rad))
self.lastPoint = QPoint(endPoint)
def resizeImage(self,image, newSize):
if image.size() == newSize:
return
newImage = QImage(newSize, QImage.Format_RGB32)
newImage.fill(qRgb(255,255,255))
painter = QPainter(newImage)
painter.drawImage(QPoint(0,0), image)
self.image = newImage
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QPushButton, QGridLayout
class ClearButton(QWidget):
def __init__(self,parent=None):
super(ClearButton,self).__init__(parent)
self.initUI()
def initUI(self):
button = QPushButton("Clear Image", self)
button.move(220,0)
button.clicked.connect(self.on_click)
grid = QGridLayout()
grid.addWidget(button,1,0,1,2)
self.setLayout(grid)
def on_click(self):
parent = self.parent()
parent.scribbleArea.clearImage()
\ No newline at end of file
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QPushButton, QLineEdit, QLabel, QGridLayout
class TestWidget(QWidget):
def __init__(self,parent=None):
super(TestWidget,self).__init__(parent)
self.initUI()
def initUI(self):
button = QPushButton("Test", self)
lbl = QLabel(self)
lbl.setText('Results :')
self.qle = QLineEdit(self)
self.qle.setReadOnly(True)
button.clicked.connect(self.on_click)
grid = QGridLayout()
grid.addWidget(lbl,1,0)
grid.addWidget(self.qle,1,1)
grid.addWidget(button,1,2)
self.setLayout(grid)
def on_click(self):
parent = self.parent()
parent.scribbleArea.clearImage()
\ No newline at end of file
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QPushButton, QLineEdit, QLabel, QGridLayout
class TrainWidget(QWidget):
def __init__(self,parent=None):
super(TrainWidget,self).__init__(parent)
self.initUI()
def initUI(self):
lbl = QLabel(self)
lbl.setText('Label : ')
self.qle = QLineEdit(self)
button = QPushButton("Save", self)
button.clicked.connect(self.on_click)
grid = QGridLayout()
grid.addWidget(lbl,1,0)
grid.addWidget(self.qle,1,1)
grid.addWidget(button,1,2)
self.setLayout(grid)
def on_click(self):
parent = self.parent()
parent.scribbleArea.saveImage(self.qle.text())
parent.scribbleArea.clearImage()
\ No newline at end of file
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QAction, QApplication, QWidget,QGridLayout)
from board import Board
from clearButton import ClearButton
from trainWidget import TrainWidget
from testWidget import TestWidget
class MainWindow(QWidget):
def __init__(self,parent=None):
super(MainWindow, self).__init__(parent)
self.scribbleArea = Board()
self.button = ClearButton()
self.train = TrainWidget()
self.test = TestWidget()
grid = QGridLayout()
grid.addWidget(self.scribbleArea,1,0)
grid.addWidget(self.button,2,0)
grid.addWidget(self.train,3,0)
grid.addWidget(self.test,4,0)
self.setLayout(grid)
self.setWindowTitle("number ubu")
self.resize(512, 650)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
import sys
import time
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QGraphicsView, QGraphicsScene,QPushButton, QVBoxLayout, QGraphicsLineItem
from PyQt5.QtGui import QPainter, QColor, QFont, QPen
from PyQt5.QtCore import Qt, QRectF, QPointF, QLineF
class Window(QWidget):
def __init__(self):
super().__init__()
self.View = ViewDT(self)
self.button = QPushButton('Clear', self)
self.button.clicked.connect(self.handleClearView)
layout = QVBoxLayout(self)
layout.addWidget(self.View)
layout.addWidget(self.button)
def handleClearView(self):
self.View.scene().clear()
class ViewDT(QGraphicsView):
def __init__(self,parent):
QGraphicsView.__init__(self,parent)
self.setScene(QGraphicsScene(self))
self.setSceneRect(QRectF(self.viewport().rect()))
self.test = False
self.start = 0
self.end = 0
def mousePressEvent(self,event):
self.test = True
self.__start = event.pos()
self.start = QPointF(self.mapToScene(event.pos()))
def mouseMoveEvent(self,event):
self.end = QPointF(self.mapToScene(event.pos()))
if self.start != self.end and self.test is True:
self.scene().addItem(QGraphicsLineItem(QLineF(self.start,self.end)))
self.start = self.end
def mouseReleaseEvent(self, event):
self.test = False
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())
\ No newline at end of file
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD license as follows:
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
## * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
## the names of its contributors may be used to endorse or promote
## products derived from this software without specific prior written
## permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
## $QT_END_LICENSE$
##
#############################################################################
from PyQt5.QtCore import QDir, QPoint, QRect, QSize, Qt
from PyQt5.QtGui import QImage, QImageWriter, QPainter, QPen, qRgb
from PyQt5.QtWidgets import (QAction, QApplication, QColorDialog, QFileDialog,
QInputDialog, QMainWindow, QMenu, QMessageBox, QWidget)
from PyQt5.QtPrintSupport import QPrintDialog, QPrinter
class ScribbleArea(QWidget):
def __init__(self, parent=None):
super(ScribbleArea, self).__init__(parent)
self.setAttribute(Qt.WA_StaticContents)
self.modified = False
self.scribbling = False
self.myPenWidth = 1
self.myPenColor = Qt.blue
self.image = QImage()
self.lastPoint = QPoint()
def openImage(self, fileName):
loadedImage = QImage()
if not loadedImage.load(fileName):
return False
newSize = loadedImage.size().expandedTo(self.size())
self.resizeImage(loadedImage, newSize)
self.image = loadedImage
self.modified = False
self.update()
return True
def saveImage(self, fileName, fileFormat):
visibleImage = self.image
self.resizeImage(visibleImage, self.size())
if visibleImage.save(fileName, fileFormat):
self.modified = False
return True
else:
return False
def setPenColor(self, newColor):
self.myPenColor = newColor
def setPenWidth(self, newWidth):
self.myPenWidth = newWidth
def clearImage(self):
self.image.fill(qRgb(255, 255, 255))
self.modified = True
self.update()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.lastPoint = event.pos()
self.scribbling = True
def mouseMoveEvent(self, event):
if (event.buttons() & Qt.LeftButton) and self.scribbling:
self.drawLineTo(event.pos())
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and self.scribbling:
self.drawLineTo(event.pos())
self.scribbling = False
def paintEvent(self, event):
painter = QPainter(self)
dirtyRect = event.rect()
painter.drawImage(dirtyRect, self.image, dirtyRect)
def resizeEvent(self, event):
if self.width() > self.image.width() or self.height() > self.image.height():
newWidth = max(self.width() + 128, self.image.width())
newHeight = max(self.height() + 128, self.image.height())
self.resizeImage(self.image, QSize(newWidth, newHeight))
self.update()
super(ScribbleArea, self).resizeEvent(event)
def drawLineTo(self, endPoint):
painter = QPainter(self.image)
painter.setPen(QPen(self.myPenColor, self.myPenWidth, Qt.SolidLine,
Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, endPoint)
self.modified = True
rad = self.myPenWidth / 2 + 2
self.update(QRect(self.lastPoint, endPoint).normalized().adjusted(-rad, -rad, +rad, +rad))
self.lastPoint = QPoint(endPoint)
def resizeImage(self, image, newSize):
if image.size() == newSize:
return
newImage = QImage(newSize, QImage.Format_RGB32)
newImage.fill(qRgb(255, 255, 255))
painter = QPainter(newImage)
painter.drawImage(QPoint(0, 0), image)
self.image = newImage
def print_(self):
printer = QPrinter(QPrinter.HighResolution)
printDialog = QPrintDialog(printer, self)
if printDialog.exec_() == QPrintDialog.Accepted:
painter = QPainter(printer)
rect = painter.viewport()
size = self.image.size()
size.scale(rect.size(), Qt.KeepAspectRatio)
painter.setViewport(rect.x(), rect.y(), size.width(), size.height())
painter.setWindow(self.image.rect())
painter.drawImage(0, 0, self.image)
painter.end()
def isModified(self):
return self.modified
def penColor(self):
return self.myPenColor
def penWidth(self):
return self.myPenWidth
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.saveAsActs = []
self.scribbleArea = ScribbleArea()
self.setCentralWidget(self.scribbleArea)
self.createActions()
self.createMenus()
self.setWindowTitle("Scribble")
self.resize(500, 500)
def closeEvent(self, event):
if self.maybeSave():
event.accept()
else:
event.ignore()
def open(self):
if self.maybeSave():
fileName, _ = QFileDialog.getOpenFileName(self, "Open File",
QDir.currentPath())
if fileName:
self.scribbleArea.openImage(fileName)
def save(self):
action = self.sender()
fileFormat = action.data()
self.saveFile(fileFormat)
def penColor(self):
newColor = QColorDialog.getColor(self.scribbleArea.penColor())
if newColor.isValid():
self.scribbleArea.setPenColor(newColor)
def penWidth(self):
newWidth, ok = QInputDialog.getInt(self, "Scribble",
"Select pen width:", self.scribbleArea.penWidth(), 1, 50, 1)
if ok:
self.scribbleArea.setPenWidth(newWidth)
def about(self):
QMessageBox.about(self, "About Scribble",
"<p>The <b>Scribble</b> example shows how to use "
"QMainWindow as the base widget for an application, and how "
"to reimplement some of QWidget's event handlers to receive "
"the events generated for the application's widgets:</p>"
"<p> We reimplement the mouse event handlers to facilitate "
"drawing, the paint event handler to update the application "
"and the resize event handler to optimize the application's "
"appearance. In addition we reimplement the close event "
"handler to intercept the close events before terminating "
"the application.</p>"
"<p> The example also demonstrates how to use QPainter to "
"draw an image in real time, as well as to repaint "
"widgets.</p>")
def createActions(self):
self.openAct = QAction("&Open...", self, shortcut="Ctrl+O",
triggered=self.open)
for format in QImageWriter.supportedImageFormats():
format = str(format)
text = format.upper() + "..."
action = QAction(text, self, triggered=self.save)
action.setData(format)
self.saveAsActs.append(action)
self.printAct = QAction("&Print...", self,
triggered=self.scribbleArea.print_)
self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q",
triggered=self.close)
self.penColorAct = QAction("&Pen Color...", self,
triggered=self.penColor)
self.penWidthAct = QAction("Pen &Width...", self,
triggered=self.penWidth)
self.clearScreenAct = QAction("&Clear Screen", self, shortcut="Ctrl+L",
triggered=self.scribbleArea.clearImage)
self.aboutAct = QAction("&About", self, triggered=self.about)
self.aboutQtAct = QAction("About &Qt", self,
triggered=QApplication.instance().aboutQt)
def createMenus(self):
self.saveAsMenu = QMenu("&Save As", self)
for action in self.saveAsActs:
self.saveAsMenu.addAction(action)
fileMenu = QMenu("&File", self)
fileMenu.addAction(self.openAct)
fileMenu.addMenu(self.saveAsMenu)
fileMenu.addAction(self.printAct)
fileMenu.addSeparator()
fileMenu.addAction(self.exitAct)
optionMenu = QMenu("&Options", self)
optionMenu.addAction(self.penColorAct)
optionMenu.addAction(self.penWidthAct)
optionMenu.addSeparator()
optionMenu.addAction(self.clearScreenAct)
helpMenu = QMenu("&Help", self)
helpMenu.addAction(self.aboutAct)
helpMenu.addAction(self.aboutQtAct)
self.menuBar().addMenu(fileMenu)
self.menuBar().addMenu(optionMenu)
self.menuBar().addMenu(helpMenu)
def maybeSave(self):
if self.scribbleArea.isModified():
ret = QMessageBox.warning(self, "Scribble",
"The image has been modified.\n"
"Do you want to save your changes?",
QMessageBox.Save | QMessageBox.Discard |
QMessageBox.Cancel)
if ret == QMessageBox.Save:
return self.saveFile('png')
elif ret == QMessageBox.Cancel:
return False
return True
def saveFile(self, fileFormat):
initialPath = QDir.currentPath() + '/untitled.' + fileFormat
fileName, _ = QFileDialog.getSaveFileName(self, "Save As", initialPath,
"%s Files (*.%s);;All Files (*)" % (fileFormat.upper(), fileFormat))
if fileName:
return self.scribbleArea.saveImage(fileName, fileFormat)
return False
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
...@@ -2,19 +2,19 @@ ...@@ -2,19 +2,19 @@
"cells": [ "cells": [
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 1, "execution_count": 57,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
"data": { "data": {
"text/plain": [ "text/plain": [
"SVC(C=0.1, cache_size=200, class_weight=None, coef0=0.0,\n", "SVC(C=0.1, cache_size=200, class_weight=None, coef0=0.0,\n",
" decision_function_shape='ovr', degree=3, gamma=0.001, kernel='rbf',\n", " decision_function_shape=None, degree=3, gamma=0.001, kernel='rbf',\n",
" max_iter=-1, probability=False, random_state=None, shrinking=True,\n", " max_iter=-1, probability=False, random_state=None, shrinking=True,\n",
" tol=0.001, verbose=False)" " tol=0.001, verbose=False)"
] ]
}, },
"execution_count": 1, "execution_count": 57,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -64,7 +64,7 @@ ...@@ -64,7 +64,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 2, "execution_count": 42,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -76,7 +76,7 @@ ...@@ -76,7 +76,7 @@
" 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9])" " 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9])"
] ]
}, },
"execution_count": 2, "execution_count": 42,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -87,10 +87,8 @@ ...@@ -87,10 +87,8 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 3, "execution_count": 84,
"metadata": { "metadata": {},
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"#การทดสอบ\n", "#การทดสอบ\n",
...@@ -111,7 +109,7 @@ ...@@ -111,7 +109,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 4, "execution_count": 85,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -120,7 +118,7 @@ ...@@ -120,7 +118,7 @@
"array([7])" "array([7])"
] ]
}, },
"execution_count": 4, "execution_count": 85,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -132,7 +130,7 @@ ...@@ -132,7 +130,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 5, "execution_count": 91,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -140,7 +138,7 @@ ...@@ -140,7 +138,7 @@
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"Classification report for classifier SVC(C=0.1, cache_size=200, class_weight=None, coef0=0.0,\n", "Classification report for classifier SVC(C=0.1, cache_size=200, class_weight=None, coef0=0.0,\n",
" decision_function_shape='ovr', degree=3, gamma=0.001, kernel='rbf',\n", " decision_function_shape=None, degree=3, gamma=0.001, kernel='rbf',\n",
" max_iter=-1, probability=False, random_state=None, shrinking=True,\n", " max_iter=-1, probability=False, random_state=None, shrinking=True,\n",
" tol=0.001, verbose=False):\n", " tol=0.001, verbose=False):\n",
" precision recall f1-score support\n", " precision recall f1-score support\n",
...@@ -188,7 +186,7 @@ ...@@ -188,7 +186,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 6, "execution_count": 70,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -196,10 +194,10 @@ ...@@ -196,10 +194,10 @@
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"Fitting the classifier to the training set\n", "Fitting the classifier to the training set\n",
"done in 0.436s\n", "done in 0.234s\n",
"Best estimator found by grid search:\n", "Best estimator found by grid search:\n",
"SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,\n", "SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,\n",
" decision_function_shape='ovr', degree=3, gamma=0.0005, kernel='rbf',\n", " decision_function_shape=None, degree=3, gamma=0.0005, kernel='rbf',\n",
" max_iter=-1, probability=False, random_state=None, shrinking=True,\n", " max_iter=-1, probability=False, random_state=None, shrinking=True,\n",
" tol=0.001, verbose=False)\n" " tol=0.001, verbose=False)\n"
] ]
...@@ -250,7 +248,7 @@ ...@@ -250,7 +248,7 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.5.2" "version": "3.6.1"
} }
}, },
"nbformat": 4, "nbformat": 4,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment