5 Object Oriented and Graphical User Interface
5 Object Oriented and Graphical User Interface
Nanjing University
Graphical User Interface (GUI) 4
Nanjing University
5
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
Nanjing University
Methods of Class 10
• Method S ource
Nanjing University
Instances 11
S ource S ource
2 Create an instance——dog
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
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
Nanjing University
Use Button as an Example 16
SetLabel
SetDefault
label
Font ……
Nanjing University
17
INHERITANCE
Nanjing University
Base class & Derived Class 18
Control
Inheritance Button
BitmapButton
Nanjing University
Derived Class/Subclass 19
S ource
Single Multiple
Inheritance Inheritance
Nanjing University
Subclass Definition and Override 20
F ile
F ile
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
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
• 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
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))
Nanjing University
29
USEFUL GUI
WIDGETS
Nanjing University
Example of Application 30
Menu
Static text
Input frame
List Frame
Button
Nanjing University
Button and Family 31
• Useful Button:
– wx.Button:Text Button
– wx.BitmapButton:Bitmap Button
– wx.ToggleButton:Toggle Button
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
• Static text(label):
– Class:wx.StaticText
• Textbox:
– Class:wx.TextCtrl
Nanjing University
ListCtrl 35
List模式
Nanjing University
RadioBox and CheckBox 36
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
LAYOUT
MANAGEMENT
Nanjing University
Layout Management 39
Nanjing University
sizer 40
Nanjing University
Example of sizer 41
BoxSizer
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
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
OTHER GUI
LIBRARIES
Nanjing University
GUI Implement in Python 45
Nanjing University
PyQt 46
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
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
Nanjing University
PyGTK 52
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
Nanjing University
55
COMPREHENSIVE
APPLICATION
Nanjing University
56
Graphical User Interface (GUI)
Nanjing University
57
Summary
Nanjing University