python学习
MOOCPython玩转数据
面向对象和图形用户界面
GUI与面向对象
# -*- coding: utf-8 -*-
#定义狗的父类
class Dog:
"define dog class"
#计数器,累积实例化的次数
counter=0
def __init__(self,name):
self.name=name
Dog.counter+=1
def greet(self):
print("Hi,I am called %s,my number is %d"%(self.name,Dog.counter))
if __name__=="__main__":
dog=Dog("Paul")
dog.greet()
#定义子类
class BarkingDog(Dog):
"define subclass BarkingDog"
def greet(self):
"initial subclass"
print("Woof!I am %s,my number is %d"%(self.name,Dog.counter))
if __name__=="__main__":
dog=BarkingDog("Zoe")
dog.greet()
抽象
定义一个表示班级的类,数据属性包括班主任姓名和学生姓名列表,具有以下方法:
(1)init()方法对数据进行初始化,以班主任的姓名初始化;
(2)add():加入一个学生姓名;
(3)remove():按照姓名移除学生;
(4)print_all():输出班主任姓名和所有学生名单。
先自己写一写这个程序然后填空(请把结果写在同一行上,中间用一个半角分号分隔)。
classcounter.py
class roster:
"students and teacher class"
teacher = ""
students = [ ]
def __init__(self, tn = 'Niuyun'):
self.teacher = tn
def add(self, sn):
self.students.append(sn)
def remove(self, sn):
self.students.remove(sn)
def print_all(self):
print("Teacher:",self.teacher)
print("Students:",self.students)
继承
BMI Calculating.py
# -*- coding: utf-8 -*-
"""
@author: zhuyue
"""
class BMI:
def __init__(self,height,weight):
self.bmi=weight/height**2
def printBMI(self):
print("Your BMI is {:.2f}".format(self.bmi))
if __name__ == "__main__":
h = float(input('Please enter your height(m): '))
w = float(input('Please input your weight(kg): '))
x = BMI(h, w)
x.printBMI()
class ChinaBMI(BMI):
def printBMI(self):
print("你的BMI是{:.2f}".format(self.bmi))
if self.bmi<18.5:
print("偏瘦, 相关疾病发病的危险性低(但其他疾病危险性增加)。")
elif 18.5 <= self.bmi < 24:
print("正常, 相关疾病发病的危险性为平均水平。")
elif 24 <= self.bmi < 27:
print("偏胖, 相关疾病发病的危险性为增加。")
elif 27<=self.bmi<=30:
print("肥胖, 相关疾病发病的危险性为中度增加。")
else:
print("重度肥胖, 相关疾病发病的危险性严重增加。")
if __name__ == "__main__":
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
x=ChinaBMI(height,weight)
x.printBMI()
GUI的基本框架
创建一个简单的wxPython程序
firstwxPython.py
import wx
app=wx.App()
frame=wx.Frame(None,title="Hello,World!")
frame.Show(True)
app.MainLoop()
改变一下
面板被放到窗口中,而静态文本对象被放到面板中。
mouse.py
# -*- coding: utf-8 -*-
import wx
class MyApp(wx.App):
def OnInit(self):
frame = wx.Frame(None, title="Hello,World!")
frame.Show(True)
return True
if __name__ == "__main__":
app=MyApp()
app.MainLoop()
组建:
helloworld.py
# -*- coding: utf-8 -*-
import wx
class Frame1(wx.Frame):
def __init__(self,superior):
wx.Frame.__init__(self,parent=superior,title="Example",
pos=(100,200),size=(350,200))
panel=wx.Panel(self)
text1=wx.TextCtrl(panel,value="Hello,World!",size=(350,200))
if __name__ == '__main__':
app =wx.App()
frame = Frame1(None)
frame.Show(True)
app.MainLoop()
事件处理机制:
mouse_event.py
# -*- coding: utf-8 -*-
#鼠标左键的抬起事件绑定在panel的Onclick上
import wx
class Frame1(wx.Frame):
def __init__(self,superior):
wx.Frame.__init__(self,parent=superior,title="Example",
pos=(100,200),size=(350,200))
self.panel=wx.Panel(self)
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))
if __name__ == '__main__':
app =wx.App()
frame = Frame1(None)
frame.Show(True)
app.MainLoop()
GUI常用组件
按钮
菜单
静态文本和
列表
单选框、复选框
mouse_event2.py
实现在程序Frame中按下鼠标左键时,在鼠标按下的位置出现一个Button.
# -*- coding: utf-8 -*-
#鼠标左键的抬起事件绑定在panel的Onclick上
import wx
class Frame1(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self,parent,title="title")
self.panel=wx.Panel(self)
self.panel.Bind(wx.EVT_LEFT_UP,self.OnClick)
self.Show(True)
def OnClick(self,event):
posm=event.GetPosition()
wx.Button(self.panel,label="Hi~~~",pos=(posm.x,posm.y))
if __name__ == '__main__':
app =wx.App()
frame = Frame1(None,"Hello Python!")
app.MainLoop()
布局管理
helloworldbtn.py
# -*- coding: utf-8 -*-
import wx
class Frame1(wx.Frame):
def __init__(self,superior):
wx.Frame.__init__(self, parent = superior, title = "Hello World in wxPython")
#创建自动调用尺寸的panel容器
panel = wx.Panel(self)
#创建一个BoxSizer实例,方向是垂直方向
sizer = wx.BoxSizer(wx.VERTICAL)
#创建子窗口部件
self.text1= wx.TextCtrl(panel, value = "Hello, World!", size = (200,180), style = wx.TE_MULTILINE)
#使用sizer的Add()方法将每个子窗口添加给sizer
sizer.Add(self.text1, 0, wx.ALIGN_TOP | wx.EXPAND)
#添加按钮子窗口部件
button = wx.Button(panel, label = "Click Me")
sizer.Add(button)
#调用容器的SetSizer(sizer)方法
panel.SetSizerAndFit(sizer)
panel.Layout()
#鼠标左键的抬起事件绑定在panel的Onclick上
self.Bind(wx.EVT_BUTTON,self.OnClick,button)
self.Show(True)
def OnClick(self, text):
self.text1.AppendText("\nHello, World!")
if __name__ == '__main__':
app=wx.App()
frame=Frame1(None)
app.MainLoop()
其他GUI库
PyQt
# -*- coding: utf-8 -*-
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_())
Tkinter
# -*- coding: utf-8 -*-
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()
PyGTK
单元测试
# -*- coding: utf-8 -*-
class Animal(object):
def __init__(self, name):
self.name = name
def getInfo(self):
print("This animal's name:", self.name)
def sound(self):
print("The sound of this animal goes?")
class Dog(Animal):
def __init__(self, name, size):
self.name = name
self.__size = size
def getInfo(self):
print("This dog's name:", self.name)
print("This dog’s size:", self.__size)
if __name__=="__main__":
dog = Dog('wangcai', 'small')
dog.getInfo()
dog.sound()
class Cat(Animal):
def sound(self):
print("The sound of cat goes meow ~")
if __name__=="__main__":
cat = Cat('kawaii')
cat.getInfo()
cat.sound()