面向对象与GUI编程

对应教学日历:讲次 11-12


一、面向对象基础

面向对象程序设计将数据以及对数据的操作放在一起,对象是程序的基本单元。

类与对象

  • :建立对象的模板,定义事物的属性和行为
  • 对象:类的实例,抽象与具体的关系

同一类的不同实例具有:

  • 相同的属性集合
  • 相同的方法集合
  • 不同的对象名

类的定义

class 类名[(父类)]:
    属性
    方法

基本示例

class Dog:
    def __init__(self):
        self.sound = "wang~wang~~"
    def bark(self):
        print(self.sound)
 
bob = Dog()    # 创建对象
bob.bark()     # 调用方法

带参数的类

class Animal(object):
    def __init__(self, voice='miao'):
        self.voice = voice
    def say(self):
        print(self.voice)
 
kitty = Animal()
kitty.say()     # miao
bob = Animal('wow')
bob.say()       # wow

类的继承

class animals:
    def breath(self):
        print('breathing')
 
class dog(animals):
    def eat(self):
        print('eating')
 
bob = dog()
bob.breath()   # 继承父类方法
bob.eat()      # 自有方法

类的三种特征

特征说明
封装性将细节隐藏,通过方法接口访问
继承性子类继承父类的属性和方法
多态性同一运算符/方法,根据对象类型执行不同操作

二、tkinter GUI 编程

设计步骤

  1. 导入tkinter模块
  2. 创建GUI主窗体
  3. 添加人机交互控件并编写相应的函数
  4. 在主事件循环中等待用户触发事件响应

主窗体

from tkinter import *
root = Tk()
root.title("Mike's program")
root.geometry("400x300")
root.mainloop()

三、常用控件

1. 按钮(Button)

btn = Button(窗口, text="按钮文字", width=40, height=5,
    bg='red', command=回调函数)
btn.pack()
  • command:点击按钮时执行的函数
  • width/height:按钮尺寸
  • bg/fg:背景色/前景色
  • state:NORMAL/DISABLED/ACTIVE

2. 标签(Label)

lb = Label(root, text='金融挖掘系统1.0版',
    font=('宋体', 28), width=20, height=2)
lb.pack()
  • text:标签文本
  • font:字体字号
  • fg/bg:前景色/背景色

3. 单行文本框(Entry)

E1 = Entry(root, bd=1, font=12, width=15)
E1.place(x=60, y=10)
方法功能
get()获取文本框的值
insert(index, s)插入文本
delete(first, last)删除文本

4. 多行文本框(Text)

t = Text(root, width=30, height=20)
t.pack()
方法功能
get('1.0', END)获取全部内容
insert(index, s)插入文本
delete(first, last)删除文本

5. 消息框

from tkinter.messagebox import *
showinfo("标题", "内容")

四、布局管理

# pack() 自动布局
btn.pack()
btn.pack(side=RIGHT)
btn.pack(fill=X)
 
# place() 绝对定位
btn.place(x=60, y=100)

作业示例

小型计算器

from tkinter import *
 
def cal():
    result = eval(E1.get())
    E2.delete(0, END)
    E2.insert(END, result)
 
root = Tk()
root.title("小型计算器")
root.geometry("250x150")
L1 = Label(root, text="公式:")
L1.place(x=10, y=10)
E1 = Entry(root, bd=1, font=12, width=15)
E1.place(x=60, y=10)
L2 = Label(root, text="结果:")
L2.place(x=10, y=60)
E2 = Entry(root, bd=1, font=12, width=15)
E2.place(x=60, y=60)
B1 = Button(root, text="=", width=15, command=cal)
B1.place(x=60, y=100)
root.mainloop()

要点

  • eval() 计算字符串表达式的值
  • Entry.get() 获取输入框内容
  • Entry.delete(0, END) 清空输入框
  • Entry.insert(END, result) 插入结果

动态时钟

from tkinter import *
import time
 
def gettime():
    current = time.strftime("%H:%M:%S")
    lb.configure(text=current)
    root.after(1000, gettime)
 
root = Tk()
root.title("Clock")
lb = Label(root, text='', fg='blue', font=("Arial", 80))
lb.pack()
gettime()
root.mainloop()

要点

  • root.after(1000, gettime) 每1000ms调用一次
  • lb.configure(text=current) 动态更新标签文本

股票数据分析

from tkinter import *
 
def cal():
    name = E1.get()
    maxn = 0
    with open(name, "r") as fobj:
        for i in fobj:
            if i[:2] == "日期":
                continue
            i = i.strip()
            info = i.split(",")
            if maxn < int(info[6]):
                maxn = int(info[6])
    E2.delete(0, END)
    E2.insert(END, maxn)
 
root = Tk()
root.title("数据统计")
root.geometry("250x150")
L1 = Label(root, text="文件名:")
L1.place(x=10, y=10)
E1 = Entry(root, bd=1, font=12, width=15)
E1.place(x=60, y=10)
L2 = Label(root, text="最大值:")
L2.place(x=10, y=60)
E2 = Entry(root, bd=1, font=12, width=15)
E2.place(x=60, y=60)
B1 = Button(root, text="数据处理", width=15, command=cal)
B1.place(x=60, y=100)
root.mainloop()

随机点名程序(tkinter版)

from tkinter import *
import random
 
def cal(num):
    aList = []
    with open("student.csv", 'r') as handle:
        for i in handle:
            i = i.strip()
            info = i.split(",")
            aList.append(info[1])
    result = random.sample(aList, num)
    for i in result:
        print("{},请回答问题.".format(i))
 
root = Tk()
root.title("Random call")
one = Button(root, text='点一名学生',
    width=40, height=5, command=lambda: cal(1))
one.pack()
three = Button(root, text='点三名学生',
    width=40, height=5, command=lambda: cal(3))
three.pack()
root.mainloop()

要点

  • command=lambda: cal(1) 用lambda传递参数
  • random.sample(aList, num) 随机选取num个

作业重点

  • 类用 class 定义,__init__ 是构造方法,self 表示当前实例
  • 继承:class 子类(父类):,子类可调用父类方法
  • tkinter设计步骤:导入 → 创建窗体 → 添加控件 → mainloop()
  • Buttoncommand 参数绑定回调函数
  • Entry.get() 获取输入,Entry.delete(0, END) 清空
  • Text.get('1.0', END) 获取多行文本
  • lambda 用于在tkinter中传递参数给回调函数
  • root.after(ms, func) 实现定时调用