1. Object对象概念

Everything could be an object! 万物皆对象!

1. Objects 对象

2. Objectives学习目标

  • To understand the concept of objects and how they can simplify programs 理解对象概念及其如何简化程序
  • To be familiar with the various objects in the graphics library 熟悉图形库中的各种对象
  • To be able to create objects and call methods for graphical computations 能够创建对象并调用方法进行图形计算
  • To understand computer graphics concepts: coordinate systems and transformations 理解计算机图形概念:坐标系和变换
  • To work with both mouse and text-based input in graphics 在图形环境中处理鼠标和文本输入
  • To write simple interactive graphics programs 编写简单的交互式图形程序

3.Overview概述

Traditional vs Object-oriented 传统vs面向对象

  • Traditional传统: Data is passive, manipulated by operations 数据是被动的,由操作操纵
  • Object-oriented面向对象: Objects combine data and operations 对象结合数据和操作

Graphical User Interfaces (GUI)图形用户界面

  • Most applications use GUIs with windows, icons, buttons, menus 大多数应用使用带窗口、图标、按钮、菜单的GUI
  • Uses graphics.py library based on Tkinter 使用基于Tkinter的graphics.py库

4. The Object of Objects 对象的对象

Basic Idea基本理念

  • View complex systems as interaction of simpler objects 将复杂系统视为简单对象的交互
  • Object = active data type combining data and operations 对象=结合数据和操作的主动数据类型

Object Characteristics对象特性

  • Know stuff 包含数据: Contain data 包含数据
  • Do stuff 具有操作: Have operations 具有操作
  • Interact through messages 通过消息交互: Send messages to each other 相互发送消息

Example: Student System示例:学生系统

# Traditional approach 传统方法
def select(student_id, student_name, course_id, course_name, time, range)
select('20240001','xiaoming','20240005','Python','Tuesday','Grade two')
 
# Object-oriented approach 面向对象方法
student1 = Student('20240001','xiaoming','Grade two')
course1 = Course('20240005','python','Tuesday')
select(student1, course1)

Object Relationships对象关系

  • Objects may refer to other objects 对象可以引用其他对象
  • Example: Course object contains Instructor, Student roster, etc. 示例:课程对象包含教师、学生名单等

5. Simple Graphics Programming 简单图形编程

Using graphics.py Library 使用graphics.py库

Two location choices两种位置选择:

  1. In Python’s Lib directory with other libraries 在Python的Lib目录中
  2. In the same folder as your graphics program 在图形程序相同文件夹中

Importing the Library导入库

>>> import graphics
>>> win = graphics.GraphWin()  # Create graphics window 创建图形窗口

Alternative import method替代导入方法:

>>> from graphics import *    # Import all functions 导入所有函数
>>> win = GraphWin()          # No need for graphics. prefix 无需graphics.前缀

Graphics Window图形窗口

  • Collection of points called pixels像素
  • Default: 200×200 pixels (40,000 pixels total) 默认200×200像素
  • Coordinate system: (0,0) at upper left corner 坐标系:(0,0)在左上角
GraphWin(title, width, height)  # 构造函数
# title: default "Graphics Window"
# width: default 200
# height: default 200

Drawing Points绘制点

>>> p = Point(50, 60)      # Create point at (50,60) 在(50,60)创建点
>>> p.getX()               # Get x coordinate 获取x坐标
50
>>> p.getY()               # Get y coordinate 获取y坐标
60
>>> win = GraphWin()
>>> p.draw(win)            # Draw point in window 在窗口中绘制点

5.1 Exercise: Shapes 练习:形状绘制

Task任务

Open window titled ‘Shapes’ and draw: 打开标题为’Shapes’的窗口并绘制:

  1. Red circle centered at (100,100), radius 30 红色圆圈,中心(100,100),半径30
  2. Textual label in center of circle 圆圈中心的文本标签
  3. Square using Rectangle object 使用Rectangle对象的正方形
  4. Line segment using Line object 使用Line对象的线段
  5. Oval using Oval object 使用Oval对象的椭圆

Solution解决方案

# Open graphics window 打开图形窗口
win = GraphWin('Shapes')
 
# Draw red circle 绘制红色圆圈
center = Point(100, 100)
circ = Circle(center, 30)
circ.setFill('red')
circ.draw(win)
 
# Put label in center 在中心放置标签
label = Text(center, "Red Circle")
label.draw(win)
 
# Draw square 绘制正方形
rect = Rectangle(Point(30, 30), Point(70, 70))
rect.draw(win)
 
# Draw line segment 绘制线段
line = Line(Point(20, 30), Point(180, 165))
line.draw(win)
 
# Draw oval 绘制椭圆
oval = Oval(Point(20, 150), Point(180, 199))
oval.draw(win)

6. Using Graphical Objects 使用图形对象

Classes and Instances类和实例

  • Class类: Generic template describing object properties 描述对象属性的通用模板
  • Instance实例: Specific example of a class 类的具体示例

Example示例:

# Class: Point
# Instance: p = Point(50, 60)

Object Components对象组件

  • Attributes属性: Like variables (x, y in Point) 类似变量
  • Methods方法: Like functions (draw(), getX()) 类似函数

Constructors构造函数

<class-name>(<param1>, <param2>, ...)
# Example: p = Point(50, 60)

Methods方法类型

Accessors访问器: Get information 获取信息

p.getX()    # Returns x coordinate 返回x坐标
p.getY()    # Returns y coordinate 返回y坐标

Mutators变异器: Change object state 改变对象状态

circ.move(dx, dy)  # Move object 移动对象
circ.setFill('red') # Change fill color 改变填充颜色

Aliasing别名问题

leftEye = Circle(Point(80, 50), 5)
rightEye = leftEye          # Aliasing - both refer to same object 别名-都指向同一对象
rightEye.move(20, 0)        # Moves both eyes! 移动了两只眼睛!

Solution解决方案

Method 1方法1: Create separate objects 创建独立对象

leftEye = Circle(Point(80, 50), 5)
rightEye = Circle(Point(100, 50), 5)

Method 2方法2: Use clone method 使用clone方法

leftEye = Circle(Point(80, 50), 5)
rightEye = leftEye.clone()  # Create exact copy 创建精确副本
rightEye.move(20, 0)        # Only moves right eye 只移动右眼

6.1 Exercise: Graphing Future Value 练习:绘制未来价值图

Problem问题

Graphically display investment growth over 10 years 图形化显示10年投资增长

Pseudocode伪代码

Print introduction
Get principal and apr from user
Create GraphWin
Draw scale labels
Draw bar at position 0 with principal height
For years 1 through 10:
    Calculate principal = principal * (1 + apr)
    Draw bar for this year
Wait for user to press Enter

Implementation实现

# Create window 创建窗口
win = GraphWin("Investment Growth Chart", 320, 240)
win.setBackground("white")
 
# Set coordinate system 设置坐标系
win.setCoords(-1.75, -200, 11.5, 10400.0)
 
# Draw labels and initial bar 绘制标签和初始条
# ... (implementation details) 实现细节
 
# Wait for user input 等待用户输入
input("Press <Enter> to quit")
win.close()

Coordinate Transformation坐标变换

Problem问题: Real-world values → Window coordinates 真实世界值→窗口坐标

  • x: years 0-10 年份0-10
  • y: monetary amounts 0-10000 金额0-10000

Solution解决方案: Use setCoords() 使用setCoords()

win.setCoords(xll, yll, xur, yur)  # 设置坐标系
# (xll, yll): lower-left corner 左下角
# (xur, yur): upper-right corner 右上角
 
# Example: win.setCoords(-1.75, -200, 11.5, 10400.0)

7. Review of Graphics Classes 图形类回顾

Classes类

  • GraphWin(title, width, height)
  • Point(x, y)
  • Circle(Point(x,y), radius)
  • Text(Point(x,y), string)
  • Rectangle(Point(x,y), Point(x,y))
  • Line(Point(x,y), Point(x,y))
  • Oval(Point(x,y), Point(x,y))
  • Polygon(point1, point2, point3, ...)

Methods方法

  • object.draw(win)
  • object.setFill("color")
  • object.setOutline("color")
  • object.move(dx, dy)
  • object.clone()
  • win.setCoords(xll, yll, xur, yur)
  • win.setBackground("color")

8. Interactive Graphics 交互式图形

Event-driven Programming事件驱动编程

  • Draw interface elements (widgets) then wait for user action 绘制界面元素后等待用户操作
  • Event事件: Object encapsulating user action information 封装用户操作信息的对象

Getting Mouse Clicks获取鼠标点击

getMouse()  # Pauses and waits for mouse click 暂停并等待鼠标点击
# Returns click location as Point 返回点击位置作为Point
 
# Example示例:
clickPoint = win.getMouse()  # Wait for mouse click 等待鼠标点击
print("Clicked at:", clickPoint.getX(), clickPoint.getY())

Exercise: Draw Triangle练习:绘制三角形

Task任务: Draw triangle through three mouse clicks 通过三次鼠标点击绘制三角形

Pseudocode伪代码:

Open window
Set coordinates
Display prompt message
Get three points through mouse clicks
Draw triangle using Polygon
Change prompt message
Wait for final click to quit

Implementation实现:

win = GraphWin("Draw a Triangle", 500, 500)
win.setCoords(0.0, 0.0, 10.0, 10.0)
 
# Display prompt 显示提示
message = Text(Point(5, 0.5), "Click on three points")
message.draw(win)
 
# Get three points 获取三个点
p1 = win.getMouse()
p2 = win.getMouse() 
p3 = win.getMouse()
 
# Draw triangle 绘制三角形
triangle = Polygon(p1, p2, p3)
triangle.setFill("peachpuff")
triangle.setOutline("cyan")
triangle.draw(win)
 
# Change prompt and wait 更改提示并等待
message.setText("Click anywhere to quit.")
win.getMouse()
win.close()

Text Manipulation文本操作

message = Text(Point(5, 0.5), "Click on three points")
message.draw(win)
message.setText("Click anywhere to quit.")  # Change text 更改文本

9. Handling Textual Input 处理文本输入

Keyboard Input键盘输入

getKey()  # Waits for key press, returns string 等待按键,返回字符串
# Example: keyString = win.getKey()

Entry Widget输入框组件

# Create entry box 创建输入框
inputBox = Entry(centerPoint, width)  # width in characters 宽度以字符计
 
# Get/set text 获取/设置文本
inputStr = inputBox.getText()    # Get current text 获取当前文本
inputBox.setText("New text")     # Set new text 设置新文本

Exercise: Temperature Converter练习:温度转换器

Pseudocode伪代码:

Draw interface:
  Open window
  Set coordinates (0.0, 0.0, 3.0, 4.0)
  Text: "Celsius Temperature:"
  Text: "Fahrenheit Temperature:"
  Entry box for input (default 0.0)
  Text for output (default "")
  Button: "Convert" (Rectangle + Text)
  
Wait for mouse click
Get input from entry box
Convert Celsius to Fahrenheit
Display result in output text

Implementation实现:

# Create window and set coordinates 创建窗口并设置坐标
win = GraphWin("Temperature Converter", 400, 300)
win.setCoords(0.0, 0.0, 3.0, 4.0)
 
# Draw interface elements 绘制界面元素
Text(Point(1, 3), "Celsius Temperature:").draw(win)
Text(Point(1, 1), "Fahrenheit Temperature:").draw(win)
 
# Create input and output 创建输入和输出
inputBox = Entry(Point(2, 3), 5)
inputBox.setText("0.0")
inputBox.draw(win)
 
outputText = Text(Point(2, 1), "")
outputText.draw(win)
 
# Create button 创建按钮
button = Rectangle(Point(1, 2), Point(2, 2.5))
button.draw(win)
buttonText = Text(Point(1.5, 2.25), "Convert it")
buttonText.draw(win)
 
# Wait for click and process 等待点击并处理
win.getMouse()
 
# Convert temperature 转换温度
celsius = float(inputBox.getText())
fahrenheit = 9/5 * celsius + 32
outputText.setText(str(fahrenheit))
 
# Wait to quit 等待退出
win.getMouse()
win.close()

10. Summary总结

Key Concepts关键概念

  • Object-oriented programming面向对象编程: Objects combine data and operations 对象结合数据和操作
  • Graphics programming图形编程: Using graphics.py library 使用graphics.py库
  • Coordinate systems坐标系: Window coordinates and transformations 窗口坐标和变换
  • Interactive graphics交互式图形: Mouse and keyboard input 鼠标和键盘输入

Important Classes重要类

  • Basic shapes: Point, Circle, Rectangle, Line, Oval, Polygon
  • Interface: GraphWin, Text, Entry

Programming Patterns编程模式

  • Event-driven事件驱动: Wait for user input then respond 等待用户输入然后响应
  • Coordinate transformation坐标变换: Map real-world values to screen coordinates 将真实世界值映射到屏幕坐标
  • Object manipulation对象操作: Create, modify, and display graphical objects 创建、修改和显示图形对象

下一章