0% found this document useful (0 votes)
24 views

5 Object Oriented and Graphical User Interface

Uploaded by

maxew81693
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

5 Object Oriented and Graphical User Interface

Uploaded by

maxew81693
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Data Processing Using Python

Object-Oriented and Graphical User


Interface
ZHANG Li/Dazhuang
Nanjing University
Department of Computer Science and Technology
Department of University Basic Computer Teaching
2

Data Processing Using


Python

GUI AND OBJECT-


ORIENTED
Nanjing University
Character User Interface (CUI) 3

Nanjing University
Graphical User Interface (GUI) 4

Nanjing University
5

Data Processing Using


Python

ABSTRACTION

Nanjing University
Object-Oriented 6

• Object(Instance)
– Data and operations on specific
data

• Class
– describe the feature of object
(data & operation)

Nanjing University
7

• Have a name
• Have a square frame
Refresh Similarity • React when clicked
Quit Difference • Different functions:
Refresh、Quit

Abstraction

Nanjing University
Relationship between Class and Object 8

Object
1 Object
2
Object
Class 3

Nanjing University
Definition of Class 9

S ource S ource

class ClassName(object): class MyDate(object):


'this is a very simple
'define ClassName class' example class'
class_suite pass

Origin of all class——object

Nanjing University
Methods of Class 10

• Method S ource

Definition >>> class Dog(object):


def greet(self):
print('Hi!')

Nanjing University
Instances 11

S ource S ource

>>> class Dog(object): >>> dog = Dog()


def greet(self):
>>> dog.greet()
print('Hi!')

• Creation of instance——By calling the class object


1 Define a class——Dog

2 Create an instance——dog

3 Use attributes or methods by instance——dog.greet

Nanjing University
Instance Attributes 12

F ile

# Filename: doginsta.py
class Dog(object):
"define Dog class" Output:
Hi, I am called Paul.
def setName(self, name):
self.name = name
def greet(self):
print("Hi, I am called %s." % self.name)
if __name__ == '__main__':
dog = Dog()
dog.setName("Paul")
dog.greet()

Nanjing University
Initializing Method of Object __init__() 13

01 When a class is called, Python will create an instance

After creation, the first method Python


02
automatically calls is __init__()

The instance will be passed as the first parameter


03 (self) of the method, and all parameters in
creation will be passed to __init__()
Nanjing University
__init__() Example 14

F ile

# Filename: doginsta.py
class Dog(object):
"define Dog class"
Output:
Hi, I am called Sara.
def __init__(self, name):
self.name = name
def greet(self):
print("Hi, I am called %s." % self.name)

if __name__ == '__main__':
dog = Dog("Sara")
dog.greet()

Nanjing University
Class Attributes 15

F ile

• The data attributes (static members) # Filename: doginsta.py


of class are only variables for defined class Dog(object):
class "define Dog class“
counter = 0
• Be used after creation of class def __init__(self, name):
• Can be updated by both methods in self.name = name
Dog.counter += 1
class and main program
def greet(self):
• Independent of instances, and the print("Hi, I am %s, my number is %d" % (self.name,
modification of class attributes should Dog.counter))
if __name__ == '__main__':
use the class name dog = Dog("Zara")
dog.greet()

Nanjing University
Use Button as an Example 16

SetLabel

SetDefault
label

Quit Button Enable


size
……
pos

Font ……

Nanjing University
17

Data Processing Using


Python

INHERITANCE

Nanjing University
Base class & Derived Class 18

Control

Inheritance Button

BitmapButton

Nanjing University
Derived Class/Subclass 19

S ource

class SubClassName (ParentClass1[, ParentClass2, ...]):


'optional class documentation string'
class_suite

Single Multiple
Inheritance Inheritance

Nanjing University
Subclass Definition and Override 20

F ile
F ile

# Filename: doginsta.py # Filename: overridepro.py


class Dog(object): class BarkingDog (Dog):
"define Dog class“ "define subclass BarkingDog"
counter = 0 def greet(self):
def __init__(self, name): "initial subclass"
self.name = name print("Woof! I am %s, my number is
Dog.counter += 1 %d" % (self.name, Dog.counter))
def greet(self): if __name__ == '__main__':
print("Hi, I am %s, my number is %d" % dog = BarkingDog("Zoe")
(self.name, Dog.counter)) dog.greet()

Nanjing University
BMI counting example 21

• Body mass index (BMI) is an important standard commonly used to measure the
degree of obesity and health of human body. The calculation formula is: BMI =
weight / square of height (unit kg / ㎡).
• (1) define BMI class, take height and weight as parameters of __init__(), calculate
BMI in __init__() method, output BMI with printBMI() method (keep one decimal
place), and instantiate with specific height and weight data.
(2) Define the ChinaBMI subclass on Category Chinese standard Risk of related diseases
the basis of the above definition
thin <18.5 low
and override the printBMI() method
according to the Chinese standard normal 18.5~23.9 average level
of BMI. Output the BMI category fatter 24~26.9 increase
and risk information of related
diseases after outputting BMI(keep obesity 27~29.9 moderate increase
one decimal place) and instantiate severe
≥30 serious increase
the specific height and weight data. obesity
Nanjing University
22

Data Processing Using


Python

BASIC GUI
FRAMEWORK
Nanjing University
Create a simple wxPython Program 23

File
# Filename: firstwxPython.py
import wx
app = wx.App()
frame = wx.Frame(None, title = "Hello, World!")
frame.Show(True)
app.MainLoop()

Nanjing University
24
The above case can also be modified as

# Filename: mouse.py
import wx

class MyApp(wx.App):
def OnInit(self):
frame = wx.Frame(None, title = "Hello, World!")
frame.Show()
return True
if __name__ == '__main__': The application object
app = MyApp() can also be an instance
app.MainLoop() of wx.App’s subclass

Nanjing University
Widget 25

• Widget Containers——To contain other widgets


– e.g. wx.Panel etc.

• Dynamic Widgets——Can be edited by users


– e.g. wx.Button、wx.TextCtrl、wx.ListBox etc.

• Static Widgets——Can not be edited by users


– e.g. wx.StaticBitmap、wx.StaticText、wxStaticLine etc.

• Others
– e.g. wx.ToolBar、wx.MenuBar、wx.StatusBar

Nanjing University
“Hello, World!”Again 26

File
# Filename: helloworld.py
import wx
class Frame1(wx.Frame):
def __init__(self,superior):
wx.Frame.__init__(self, parent = superior, title = "Example", pos= Frame
(100,200), size= (350,200))
panel = wx.Panel(self) Panel
text1= wx.TextCtrl(panel, value = "Hello, World!", size = (350,200))
if __name__ == '__main__': Text
app =wx.App() Control
frame = Frame1(None)
frame.Show(True)
app.MainLoop()

Nanjing University
Event Handling 27

• Basic Mechanism of GUI programs——Event Handling


• Event
– Move of mouse, left click, click on button, etc.
– Can be created by user operations or programs

• wxPython associates certain kind of event with specific code


(methods), when the event is created, related codes will be
automatically executed.
– E.g.:When a mouse move event is triggered, method OnMove() will be called

Nanjing University
“Hello, World!” Again 28

File
# Filename: mouse.py
import wx
class Frame1(wx.Frame):
def __init__(self,superior):
……
self.panel.Bind(wx.EVT_LEFT_UP, self.OnClick)
def OnClick(self, event):
posm = event.GetPosition()
wx.StaticText(parent = self.panel,label = "Hello, World!",pos = (posm.x, posm.y))

…… #create app and frame, show and execute event loop

Nanjing University
29

Data Processing Using


Python

USEFUL GUI
WIDGETS
Nanjing University
Example of Application 30

Menu
Static text
Input frame

List Frame

Button

Nanjing University
Button and Family 31

• Receive the click events and trigger corresponding operations

• Useful Button:
– wx.Button:Text Button

– wx.BitmapButton:Bitmap Button

– wx.ToggleButton:Toggle Button

• Binding events with handling methods

Nanjing University
Menu and Components 32

• Menu
– Menu bar
– Menu
– Menu items
• wxPython classes for Menu:
– wx.MenuBar
– wx.Menu
– wx.MenuItem

Nanjing University
Useful Menu Events 33

File
• Menu Events # Filename: menudemo.py

– wx.EVT_MENU
#Binding event handlers
self.Bind(wx.EVT_MENU,self.OnClickBigger,biggerItem)
self.Bind(wx.EVT_MENU,self.OnClickQuit,id=wx.ID_EXIT)

#Event handler
def OnClickBigger(self,e):
pass
def OnClickQuit(self,e):
self.Close()

Nanjing University
StaticText and TextCtrl 34

• Textbox is used to receive user input or display information


from programs

• Static text(label):
– Class:wx.StaticText

• Textbox:
– Class:wx.TextCtrl

– Useful setting:single line, multiple lines, rich text

Nanjing University
ListCtrl 35

• List is used to display multiple factors for user


to choose
• List can be built by following 4 ways:
– wx.LC_ICON(icon) Report 模式
– wx.LC_SMALL_ICON(small icon)
– wx.LC_LIST(list)
– wx.LC_REPORT (report)

List模式

Nanjing University
RadioBox and CheckBox 36

• Radiobox is used to select


multiple objects from a
selectable set

• Checkbox is used to choose


from a mutually exclusive
set.

Nanjing University
Example 37

# Filename: helloworldbtn.py
import wx
class Frame1(wx.Frame):
def __init__(self, superior):
wx.Frame.__init__(self, parent = superior, title = "Hello World in wxPython")
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
self.text1= wx.TextCtrl(panel, value = "Hello, World!", size = (200,180), style = wx.TE_MULTILINE)
sizer.Add(self.text1, 0, wx.ALIGN_TOP | wx.EXPAND)
button = wx.Button(panel, label = "Click Me")
sizer.Add(button)
panel.SetSizerAndFit(sizer)
panel.Layout()
self.Bind(wx.EVT_BUTTON,self.OnClick,button)
def OnClick(self, text):
self.text1.AppendText("\nHello, World!")

Nanjing University
38

Data Processing Using


Python

LAYOUT
MANAGEMENT
Nanjing University
Layout Management 39

• Absolute position – Each window widget can explicitly appoint


its position and size when created.
– Weakness:Limited Flexibility
– Hard to modify the size
– Influenced by device, OS, even fonts
• Flexible layout solution - sizer
– Every sizer has its own strategy.
– Developer chooses sizer with proper strategy, inputs the widget and
appoints the demands

Nanjing University
sizer 40

• Sizer is not a container or widget, but a layout algorithm


• Sizer allows nesting
• Useful sizer in wxPython
– wx.BoxSizer
– wx.FlexGridSizer
– wx.GridSizer
– wx.GridBagSizer
– wx.StaticBoxSizer

Nanjing University
Example of sizer 41

BoxSizer GridSizer FlexGridSizer

BoxSizer

All widgets are with the Height and width


same size, one direction is
are decided by the
fixed and the layout
expands to the other side. largest widget.
Nanjing University
Steps to use sizer 42

01
Create a container to automatically 02
call sizer, like panel
Create sizer
03
Create sub-windows 04
(window widgets) Use Add() method to add
05 every sub-window to sizer

Call SetSizer(sizer) method of container

Nanjing University
Example 43

# Filename: helloworldbtn.py
import wx
class Frame1(wx.Frame):
def __init__(self,superior):
wx.Frame.__init__(self, parent = superior, title = "Hello World in wxPython")
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
self.text1= wx.TextCtrl(panel, value = "Hello, World!", size = (200,180), style = wx.TE_MULTILINE)
sizer.Add(self.text1, 0, wx.ALIGN_TOP | wx.EXPAND)
button = wx.Button(panel, label = "Click Me")
sizer.Add(button)
panel.SetSizerAndFit(sizer)
panel.Layout()
self.Bind(wx.EVT_BUTTON,self.OnClick,button)
def OnClick(self, text):
self.text1.AppendText("\nHello, World!")

Nanjing University
44

Data Processing Using


Python

OTHER GUI
LIBRARIES
Nanjing University
GUI Implement in Python 45

wxPython Open source project


with great cross
Tkinter PyGTK
platform performance.
PyQT
http://wxpython.org

Nanjing University
PyQt 46

• One GUI solution of Python language

• Provide two kinds of authorization, GPL and commercial


agreements, and can be used without limit in free
software.

• Cross Platform:Can run on Microsoft Windows、Mac


OS X、Linux and other Unix-like platforms.

Nanjing University
PyQt Example 47

File
# Filename: PyQTdemo.py
import sys
from PyQt5 import QtWidgets
class TestWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Hello World!")
self.outputArea=QtWidgets.QTextBrowser()
self.helloButton=QtWidgets.QPushButton("Click Me")
self.layout=QtWidgets.QVBoxLayout()
self.layout.addWidget(self.outputArea)
self.layout.addWidget(self.helloButton)
self.setLayout(self.layout)
self.helloButton.clicked.connect(self.sayHello)
def sayHello(self):
self.outputArea.append("Hello, World!")
if __name__ == '__main__':
app=QtWidgets.QApplication(sys.argv)
testWidget=TestWidget()
testWidget.show()
sys.exit(app.exec_())
Nanjing University
Advantage and Weakness of PyQT 48

• Rich document
• Be careful of
• Experience similar to Qt、
C++ development memory leak
Advan Weak
• Most components for Qt • Large runtime size
are also available
tage ness
• C++ knowledge
• Convenient tools for PyQt,
like QtDesigner,Eric4 needed

Nanjing University
Tkinter 49

• Tkinter binds Tk GUI toolkit in Python, and is


implemented by Tcl interpreter inside Python interpreter.

• Call of Tkinter is converted into Tcl instructions, and be


interpreted by Tcl interpreter to build Python GUI.

Nanjing University
Tkinter Example 50

File
# Filename: Tkinterdemo.py
import tkinter as tk
class Tkdemo(object):
def __init__(self):
self.root=tk.Tk()
self.txt=tk.Text(self.root,width=30,height=10)
self.txt.pack()
self.button=tk.Button(self.root,text='Click me',
command=self.sayhello)
self.button.pack()
def sayhello(self):
self.txt.insert(tk.INSERT,"Hello, World!\n")
d=Tkdemo()
d.root.mainloop()

Nanjing University
Advantage and Weakness of Tkinter 51

• With the longest history, the standard


GUI for Python actually.
• Python contains standard interface for Tk Advan Weak
• Larger cost
GUI toolkits in standard Windows version. tage ness
• IDLE use Tkinter to implement GUI
• Simple to learn and use.

Nanjing University
PyGTK 52

• PyGTK is a Python package of GTK+ GUI library


• pyGTK provides a set of comprehensive graphical
elements and programming tools for desktop program
• PyGTK is a free software based on LGPL licence.
• Many famous GUI applications under GNOME are
implemented by PyGTK, including BitTorrent, GIMP and
Gedit

Nanjing University
PyGTK Example 53

File box1.show()
sw = gtk.ScrolledWindow()
#PyGTKdemo.py sw.set_policy(gtk.POLICY_AUTOMATIC,
import pygtk gtk.POLICY_AUTOMATIC)
pygtk.require('2.0') self.textview = gtk.TextView()
import gtk textbuffer = self.textview.get_buffer()
sw.add(self.textview)
class HelloWorld: sw.show()
def hello(self, widget, data=None): self.textview.show()
textbuffer = self.textview.get_buffer() box1.pack_start(sw)
startiter, enditer = textbuffer.get_bounds()
content_text = textbuffer.get_text(startiter, enditer) self.button = gtk.Button("Click Me")
content_text += "Hello, World!\n" self.button.connect("clicked", self.hello, None)
textbuffer.set_text(content_text) self.button.show()
box1.pack_start(self.button, expand=False, fill=False)
def __init__(self): self.window.show()
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_title("A Simple Example of PyGtk") def main(self):
self.window.connect("delete_event", self.delete_event) gtk.main()
self.window.connect("destroy", self.destroy)
self.window.set_border_width(10) if __name__ == "__main__":
box1 = gtk.VBox(False, 0) hello = HelloWorld()
self.window.add(box1) hello.main()

Nanjing University
Advantage and Weakness of PyGTK 54

• Bottom GTK+ provides


several kinds of elements
and functions Advan Weak • Bad performance on
• Can be used to develop tage ness Windows platform
software for GNOME
system.

Nanjing University
55

Data Processing Using


Python

COMPREHENSIVE
APPLICATION

Nanjing University
56
Graphical User Interface (GUI)

Nanjing University
57
Summary

Nanjing University

You might also like