一起玩Python程式:新手寫程式也可以這麼簡單!

函式設計(下) - 模組的無限可能!

張傑帆

National Taiwan University

函式設計(下) - 模組的無限可能!

目錄

🎯 學習目標

今天我們要建立自己的程式工具箱,打造實用小工具!

  • 📦 理解模組的概念與重要性
  • 📥 學會匯入與使用模組
  • 🔧 建立自己的自定義模組
  • 🎨 掌握pip套件管理工具
  • 📊 使用Matplotlib繪製圖表

準備好探索模組的無限可能了嗎?

Let's modularize! 🐍🚀

🧰 Python內建函式

Python提供了許多好用的內建函式,不需要import就能使用!

函式 功能 範例
print() 輸出訊息 print("Hello")
len() 取得長度 len([1, 2, 3]) → 3
type() 查看類型 type(10) → int
int(), float(), str() 型別轉換 int("5") → 5
input() 接收使用者輸入 name = input("姓名:")

📖 Python 官方文件

數學相關內建函式

# 數值運算
print(abs(-10))        # 絕對值:10
print(max(3, 7, 2))    # 最大值:7
print(min(3, 7, 2))    # 最小值:2
print(sum([1, 2, 3]))  # 總和:6
print(pow(2, 3))       # 次方:8 (2的3次方)
print(round(3.7))      # 四捨五入:4

# 範圍與序列
print(list(range(5)))           # [0, 1, 2, 3, 4]
print(list(range(1, 6)))        # [1, 2, 3, 4, 5]
print(list(range(0, 10, 2)))    # [0, 2, 4, 6, 8]

字串與串列操作

# 字串操作
text = "Python Programming"
print(text.upper())      # 轉大寫:PYTHON PROGRAMMING
print(text.lower())      # 轉小寫:python programming
print(text.split())      # 分割:['Python', 'Programming']
print(text.replace("Python", "Java"))  # 替換

# 串列操作
numbers = [3, 1, 4, 1, 5]
print(sorted(numbers))   # 排序:[1, 1, 3, 4, 5]
print(reversed(numbers)) # 反轉(回傳迭代器)

# 檢查與判斷
print("abc" in "abcdef")  # True
print(all([True, True]))  # 全部為True嗎?
print(any([False, True])) # 任一為True嗎?

進階內建函式

# enumerate() - 取得索引和值
fruits = ['蘋果', '香蕉', '橘子']
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# 輸出:
# 0: 蘋果
# 1: 香蕉
# 2: 橘子

# zip() - 配對多個序列
names = ['小明', '小華', '小美']
scores = [85, 92, 78]
for name, score in zip(names, scores):
    print(f"{name}: {score}分")

# map() - 對每個元素套用函式
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# filter() - 過濾元素
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4]

📦 模組是什麼?

生活中的模組概念

想像你的工具箱:

  • 🔧 螺絲起子組:各種尺寸的螺絲起子
  • 🔨 錘子組:不同功能的錘子
  • 📏 測量工具:尺、量角器、捲尺

模組就像工具箱裡的分類工具組,把相關功能整理在一起!

Python模組的優勢

優勢 說明 比喻
📚 程式碼重用 寫一次,到處使用 工具箱隨身帶
🗂️ 組織清晰 功能分門別類 工具分類擺放
👥 協同合作 大家共享好工具 分享工具箱
🛡️ 命名空間 避免名稱衝突 每個工具有標籤

Python模組的三大類型

┌────────────────────────────────┐
│  🏗 內建模組 (Built-in)        │
│  math, random, datetime, os... │
│  Python安裝就有,直接import     │
└────────────────────────────────┘
         ↓
┌────────────────────────────────┐
│  📦 第三方套件 (3rd Party)      │
│  matplotlib, numpy, pandas...  │
│  需要用pip安裝                  │
└────────────────────────────────┘
         ↓
┌────────────────────────────────┐
│  🔧 自定義模組 (Custom)         │
│  自己寫的.py檔案                │
│  放在同一資料夾就能import       │
└────────────────────────────────┘

常用內建模組介紹

# math - 數學運算
import math
print(math.sqrt(16))      # 開根號
print(math.ceil(3.2))     # 無條件進位:4
print(math.floor(3.8))    # 無條件捨去:3

# random - 隨機數
import random
print(random.randint(1, 100))           # 隨機整數 1-100
print(random.choice(['火', '水', '風'])) # 隨機選擇
print(random.random())                  # 0-1之間的隨機小數

# datetime - 日期時間
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# os - 作業系統
import os
print(os.getcwd())        # 目前工作目錄
print(os.listdir('.'))    # 列出檔案

📥 匯入模組的方法

方法一:基本匯入

# 匯入整個模組
import math

# 使用模組中的函式
result = math.sqrt(16)
print(f"√16 = {result}")  # 輸出:√16 = 4.0

# 使用模組中的常數
print(f"圓周率 π = {math.pi}")  # 輸出:圓周率 π = 3.141592653589793

# 查看模組有哪些功能
print(dir(math))  # 列出所有可用的函式和常數

方法二:匯入特定功能

# 只匯入需要的函式
from math import sqrt, pi, sin, cos

# 直接使用,不需要加 math.
result = sqrt(25)
print(f"√25 = {result}")  # 輸出:√25 = 5.0
print(f"π = {pi}")
print(f"sin(π/2) = {sin(pi/2)}")  # 輸出:1.0

方法三:使用別名

# 給模組取個簡短的別名
import datetime as dt
import random as rnd

# 使用別名(業界慣例)
now = dt.datetime.now()
print(f"現在時間:{now}")

num = rnd.randint(1, 10)
print(f"隨機數字:{num}")

# 也可以給函式取別名
from math import sqrt as square_root
result = square_root(16)
print(f"16的平方根:{result}")

方法四:匯入所有功能 (不建議)

# 匯入所有功能(不推薦,容易造成命名衝突)
from math import *

# 可以直接使用所有函式
result1 = sqrt(9)
result2 = sin(pi/2)
result3 = factorial(5)

# ⚠ 問題:如果有重複的名稱會被覆蓋
def sqrt(x):
    return "我的sqrt"

print(sqrt(16))  # 會呼叫你自己定義的,不是math.sqrt

⚠️ 注意: 這種方式容易造成命名衝突,只適合在互動式環境測試使用!

🔧 自定義模組實戰 (小練習1)

建立你的第一個模組

步驟1:建立模組檔案 magic_tools.py

# filepath: magic_tools.py
"""
魔法工具模組
提供各種實用的魔法函式
"""

def fire_ball(target, power=30):
    """火球術"""
    damage = power * 1.5
    return f"🔥{target}造成{damage}點火焰傷害!"


(接上頁)

def heal(target, amount=50):
    """治療術"""
    return f"✨{target}恢復{amount}點HP!"

def calculate_damage(base, multiplier=1.0):
    """傷害計算"""
    return int(base * multiplier)

# 模組級別的變數
GAME_VERSION = "1.0.0"
MAX_LEVEL = 99

# 測試程式碼(只有直接執行此檔案才會執行)
if __name__ == "__main__":
    print("測試魔法工具模組...")
    print(fire_ball("哥布林", 50))
    print(heal("勇者", 80))

使用自定義模組

步驟2:在主程式中使用

# filepath: main.py
# 匯入自定義模組
import magic_tools

# 使用模組中的函式
print(magic_tools.fire_ball("哥布林", 50))
print(magic_tools.heal("勇者", 80))

# 使用模組中的變數
print(f"遊戲版本:{magic_tools.GAME_VERSION}")
print(f"最高等級:{magic_tools.MAX_LEVEL}")

# 計算傷害
damage = magic_tools.calculate_damage(100, 1.5)
print(f"最終傷害:{damage}")

模組組織結構

建立專案資料夾結構:

my_game/
├── main.py              # 主程式
├── magic_tools.py       # 魔法工具模組
├── character_tools.py   # 角色工具模組
└── battle_system.py     # 戰鬥系統模組

character_tools.py 範例:

# filepath: character_tools.py
"""角色管理工具"""

def create_character(name, job, level=1):
    """創建角色"""
    return {
        "name": name,
        "job": job,
        "level": level,
        "hp": 100 * level,
        "mp": 50 * level
    }

def level_up(character):
    """角色升級"""
    character["level"] += 1
    character["hp"] = 100 * character["level"]
    character["mp"] = 50 * character["level"]
    print(f"🎉 {character['name']} 升到 Lv.{character['level']}!")
    return character

def show_status(character):
    """顯示角色狀態"""
    print(f"\n{'='*40}")
    print(f"⚔  角色:{character['name']}")
    print(f"🎭 職業:{character['job']}")
    print(f"⭐ 等級:Lv.{character['level']}")
    print(f"❤  HP:{character['hp']}")
    print(f"💙 MP:{character['mp']}")
    print(f"{'='*40}\n")

☕ 休息時間

整合多個模組

# filepath: main.py
"""主程式:整合所有模組"""

import magic_tools
import character_tools

# 創建角色
hero = character_tools.create_character("亞瑟", "騎士", 5)
character_tools.show_status(hero)

# 使用魔法
print(magic_tools.fire_ball("暗黑騎士", 60))
print(magic_tools.heal(hero["name"], 50))

# 角色升級
hero = character_tools.level_up(hero)
character_tools.show_status(hero)

🎨 套件管理與pip

pip 是Python的套件管理工具,就像應用程式商店!

# 檢查pip版本
pip --version
# 安裝套件
pip install matplotlib
# 安裝特定版本
pip install numpy==1.21.0
# 升級套件
pip install --upgrade requests
# 列出已安裝的套件
pip list
# 顯示套件資訊
pip show matplotlib
# 卸載套件
pip uninstall pandas

常用的Python套件

套件名稱 用途 安裝指令
📊 matplotlib 資料視覺化、繪圖 pip install matplotlib
🔢 numpy 數值計算、陣列處理 pip install numpy
🐼 pandas 資料分析、表格處理 pip install pandas
🌐 requests HTTP請求、網路爬蟲 pip install requests
🖼️ Pillow 圖片處理 pip install Pillow
🎮 pygame 遊戲開發 pip install pygame

requirements.txt

建立專案的套件清單:

# filepath: requirements.txt
matplotlib>=3.5.0
numpy>=1.21.0
pandas>=1.3.0
requests>=2.28.0

批次安裝所有需求套件:

pip install -r requirements.txt

匯出當前環境的套件清單:

pip freeze > requirements.txt

📊 Matplotlib繪圖魔法

安裝Matplotlib

pip install matplotlib

第一個圖表:折線圖

import matplotlib.pyplot as plt

# 準備資料
days = [1, 2, 3, 4, 5, 6, 7]
experience = [100, 250, 450, 700, 1000, 1350, 1750]

# 繪製折線圖
plt.plot(days, experience, marker='o', linestyle='-', 
         color='blue', linewidth=2, markersize=8)

# 設定標題和標籤
plt.title('每日經驗值成長 📈', fontsize=16)
plt.xlabel('天數', fontsize=12)
plt.ylabel('經驗值', fontsize=12)

# 加上格線
plt.grid(True, alpha=0.3)

# 顯示圖表
plt.show()

柱狀圖:角色屬性比較

import matplotlib.pyplot as plt

# 角色屬性資料
characters = ['勇者', '魔法師', '弓箭手', '戰士']
attack = [85, 70, 90, 95]
defense = [80, 60, 65, 90]

# 設定柱狀圖位置
x = range(len(characters))
width = 0.35

# 繪製並排柱狀圖
plt.bar([i - width/2 for i in x], attack, width, 
        label='攻擊力', color='#ff6b6b')
plt.bar([i + width/2 for i in x], defense, width, 
        label='防禦力', color='#4ecdc4')

# 設定圖表
plt.xlabel('角色', fontsize=12)
plt.ylabel('數值', fontsize=12)
plt.title('角色屬性比較 ⚔', fontsize=16)
plt.xticks(x, characters)
plt.legend()
plt.grid(axis='y', alpha=0.3)

plt.show()

圓餅圖:技能使用分布

import matplotlib.pyplot as plt

# 技能使用次數
skills = ['火球術', '治療術', '冰凍術', '雷擊術', '防禦術']
usage = [35, 25, 15, 15, 10]

# 設定顏色
colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#f9ca24', '#95afc0']

# 凸顯最常使用的技能
explode = (0.1, 0, 0, 0, 0)

# 繪製圓餅圖
plt.pie(usage, labels=skills, autopct='%1.1f%%', 
        colors=colors, startangle=90, explode=explode,
        shadow=True)

plt.title('技能使用分布 🎯', fontsize=16)
plt.axis('equal')  # 確保圓形

plt.show()

散點圖:怪物分布圖

import matplotlib.pyplot as plt
import random

# 生成隨機怪物座標
monster_x = [random.randint(0, 100) for _ in range(50)]
monster_y = [random.randint(0, 100) for _ in range(50)]
monster_size = [random.randint(20, 200) for _ in range(50)]

# 繪製散點圖
plt.scatter(monster_x, monster_y, s=monster_size, 
           alpha=0.5, c=monster_size, cmap='Reds')

plt.colorbar(label='怪物等級')
plt.title('地圖上的怪物分布 🗺', fontsize=16)
plt.xlabel('X座標')
plt.ylabel('Y座標')
plt.grid(True, alpha=0.3)

plt.show()

進階應用:多子圖布局

import matplotlib.pyplot as plt
import numpy as np

# 創建2x2的子圖
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.suptitle('RPG遊戲數據分析 📊', fontsize=18)

# 子圖1:經驗值曲線
x = np.linspace(0, 10, 100)
axes[0, 0].plot(x, np.exp(x/3), 'b-', linewidth=2)
axes[0, 0].set_title('經驗值成長曲線')
axes[0, 0].set_xlabel('等級')
axes[0, 0].set_ylabel('所需經驗值')
axes[0, 0].grid(True, alpha=0.3)

# 子圖2:角色屬性
axes[0, 1].bar(['HP', 'MP', 'ATK', 'DEF'], [100, 80, 90, 85],
              color=['red', 'blue', 'orange', 'green'])
axes[0, 1].set_title('角色屬性')
axes[0, 1].set_ylabel('數值')

# 子圖3:敵人分布
axes[1, 0].scatter(np.random.rand(50), np.random.rand(50), 
                  s=100, alpha=0.6, c='red')
axes[1, 0].set_title('敵人分布')
axes[1, 0].set_xlabel('X座標')
axes[1, 0].set_ylabel('Y座標')

# 子圖4:元素分布
axes[1, 1].pie([30, 25, 25, 20], 
              labels=['火🔥', '水💧', '風🌪', '土🌱'],
              autopct='%1.1f%%', startangle=90)
axes[1, 1].set_title('元素分布')

plt.tight_layout()
plt.show()

儲存圖表

import matplotlib.pyplot as plt

# 繪製圖表
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.title('我的圖表')

# 儲存為PNG檔案
plt.savefig('my_chart.png', dpi=300, bbox_inches='tight')

# 儲存為PDF檔案
plt.savefig('my_chart.pdf', bbox_inches='tight')

# 顯示圖表
plt.show()

小練習2

🎯 任務:建立資料視覺化工具

使用Matplotlib繪製一個「每週學習時數統計圖」:

要求:

  1. 準備一週7天的學習時數資料
  2. 繪製折線圖或柱狀圖
  3. 加上標題、軸標籤、格線
  4. 使用不同顏色美化圖表

提示:

import matplotlib.pyplot as plt

# 你的資料
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
hours = [2, 3, 2.5, 4, 3, 5, 4]

# 開始繪製你的圖表
plt.figure(figsize=(10, 6))
# ...你的程式碼...
plt.show()

💡 進階挑戰

  1. 雙科目比較:加入兩種不同科目的學習時數比較
  2. 多圖表類型:同時繪製折線圖和柱狀圖
  3. 標註重點:在圖表上標註最高值和最低值
  4. 儲存圖表:將圖表儲存為PNG檔案
# 標註最高值
max_hours = max(hours)
max_day = days[hours.index(max_hours)]
plt.annotate(f'最高: {max_hours}小時', 
            xy=(max_day, max_hours),
            xytext=(10, 10), 
            textcoords='offset points',
            arrowprops=dict(arrowstyle='->', color='red'))

# 儲存圖表
plt.savefig('study_hours.png', dpi=300, bbox_inches='tight')

🧠 運算思維總整理

模組化思維 (Modularization)

問題:寫一個RPG遊戲
       ↓
  [模組化拆解]
       ↓
  ┌────┴────┐
  │  主程式  │
  └────┬────┘
       ↓
  ┌────────────────────────┐
  │  匯入各種功能模組       │
  └────┬───────────────────┘
       ↓
  ┌────┴────┬────────┬────────┐
  │角色管理  │戰鬥系統 │物品系統│
  └─────────┴────────┴────────┘

核心概念:

  • 🧩 分而治之:把大問題拆成小問題
  • 🔄 重複利用:寫一次,到處使用
  • 📦 封裝隱藏:隱藏複雜細節,提供簡單介面
  • 🛡️ 降低耦合:模組之間互不干擾

資料視覺化思維 (Data Visualization)

選擇正確的圖表類型:

資料類型 適合的圖表 使用時機
📈 趨勢變化 折線圖 觀察數值隨時間變化
📊 數量比較 柱狀圖 比較不同類別的大小
🥧 比例分布 圓餅圖 展示各部分佔整體比例
🔵 分布關係 散點圖 觀察兩個變數的關聯

視覺化的三步驟:

1. 理解資料 → 什麼資料?要傳達什麼訊息?
2. 選擇圖表 → 哪種圖表最適合?
3. 美化呈現 → 顏色、標籤、圖例要清楚

本週總結 🎉

你學會了什麼?

✅ 模組的概念與使用

  • 了解模組的三大類型
  • 掌握import的各種方法
  • 知道如何組織程式碼

✅ 建立自定義模組

  • 創建可重用的程式碼
  • 設計清晰的模組介面
  • 整合多個模組協同工作

✅ 套件管理技能

  • 使用pip安裝套件
  • 管理專案依賴關係
  • 了解requirements.txt

✅ 資料視覺化能力

  • 用Matplotlib繪製各種圖表
  • 美化和自訂圖表樣式
  • 選擇適合的圖表類型

作業:選擇你的冒險路線! 📝

📝 選項一:基礎練習 (適合初學者)

任務:建立你的第一個自定義模組!

  1. 新增一個檔案 my_tools.py,裡面至少寫三個函式,例如:加法、計算平方、歡迎訊息等。
  2. 在主程式 main.py 匯入並呼叫這些函式,印出結果。
  3. 練習用 if __name__ == "__main__": 寫測試程式碼。

🔧 選項二:進階應用 (有點挑戰性)

任務:模組化你的RPG角色管理系統

  1. 建立 character_tools.py,實作角色創建、升級、顯示狀態等函式。
  2. 建立 battle_tools.py,實作攻擊、防禦、計算傷害等函式。
  3. main.py 整合這兩個模組,模擬一場簡單的角色對戰流程(角色創建→攻擊→升級→顯示狀態)。

🚀 選項三:創意發揮 (自由度高)

任務:打造屬於你的資料視覺化小工具

  1. 利用 Matplotlib,設計一個主題式圖表(如:學習時數、遊戲分數、運動紀錄等)。
  2. 將繪圖功能包裝成 viz_tools.py 模組,主程式呼叫即可產生圖表。
  3. 鼓勵加入進階功能:自訂顏色、標註重點、儲存圖檔、支援多種圖表類型等。

💡 給你的提示

開始前的準備:

# 1. 規劃專案結構
# 2. 先寫簡單功能
# 3. 測試每個功能
# 4. 逐步增加複雜度
# 5. 美化和優化

# 記住:先求有,再求好!

遇到問題時:

  • 📖 查看課程投影片
  • 🔍 善用AI與Google搜尋
  • 💬 和同學討論
  • 🧪 多做實驗嘗試

學習的秘訣:

「寫程式就像玩樂高,先從小零件開始,
慢慢組合成大作品。不要怕出錯,
每次除錯都是學習的機會!」

-----------------------------------------

圖片放大特效

table樣式

![Alt1](../images/1200px-National_Taiwan_University_logo.svg.png)![Alt2](../images/Python-logo-notext.svg.png) <style scoped> img[alt="Alt1"]{ background: rgba(255, 255, 255, 0); position: absolute; top: 10%; left: 10%; /* transform: translate(-50%, -50%); */ width: 200px; /* 調整圖片寬度 */ height: auto; /* 保持原始比例 */ padding:0; margin:0; z-index: 1; } img[alt="Alt2"]{ background: rgba(255, 255, 255, 0); position: absolute; top: 10%; left: 75%; /* transform: translate(-50%, -50%); */ width: 200px; /* 調整圖片寬度 */ height: auto; /* 保持原始比例 */ padding:0; margin:0; z-index: 2; } </style>

![bg left:30%](../images/pngtree-ethereal-blue-sunset-sky-texture-background-image_13623913.png)

- [數學相關內建函式](#數學相關內建函式) - [字串與串列操作](#字串與串列操作) - [進階內建函式](#進階內建函式)

- [Python模組的優勢](#python模組的優勢) - [Python模組的三大類型](#python模組的三大類型) - [常用內建模組介紹](#常用內建模組介紹)

- [方法一:基本匯入](#方法一基本匯入) - [方法二:匯入特定功能](#方法二匯入特定功能) - [方法三:使用別名](#方法三使用別名) - [方法四:匯入所有功能-不建議](#方法四匯入所有功能-不建議)

- [建立你的第一個模組](#建立你的第一個模組) - [使用自定義模組](#使用自定義模組) - [模組組織結構](#模組組織結構) - [character_tools.py 範例](#charactertools.py-範例) - [整合多個模組](#整合多個模組)

- [常用的Python套件](#常用的python套件) - [requirements.txt](#requirementstxt)

- [第一個圖表:折線圖](#第一個圖表折線圖) - [柱狀圖:角色屬性比較](#柱狀圖角色屬性比較) - [圓餅圖:技能使用分布](#圓餅圖技能使用分布) - [散點圖:怪物分布圖](#散點圖怪物分布圖) - [進階應用:多子圖布局](#進階應用多子圖布局) - [儲存圖表](#儲存圖表)

- [進階挑戰](#💡-進階挑戰)

- [🧠 運算思維總整理](#🧠-運算思維總整理) - [模組化思維 (Modularization)](#模組化思維-modularization) - [資料視覺化思維 (Data Visualization)](#資料視覺化思維-data-visualization)

![Alt1](image-1.png) <style scoped> img[alt="Alt1"]{ background: rgba(255, 255, 255, 0); position: absolute; top: 15%; right: 3%; /* transform: translate(-50%, -50%); */ width: 300px; /* 調整圖片寬度 */ height: auto; /* 保持原始比例 */ padding:0; margin:0; z-index: 1; } </style>

- 🖼️ 用Tkinter製作GUI視窗程式

### 常用的內建函式

![bg left:30%](image-2.png)

```python # 給模組取個簡短的別名 import matplotlib.pyplot as plt import numpy as np import pandas as pd # 使用別名(業界慣例) data = np.array([1, 2, 3, 4, 5]) plt.plot(data) plt.show() # 也可以給函式取別名 from math import sqrt as square_root result = square_root(16) ```

### 什麼是pip?

--- ## 🖼️ Tkinter GUI介面入門 ### 第一個視窗程式 ```python import tkinter as tk # 創建主視窗 window = tk.Tk() window.title("我的第一個GUI程式 🎮") window.geometry("400x300") # 寬x高 # 加入標籤 label = tk.Label(window, text="歡迎來到冒險世界!", font=("Arial", 16), fg="blue") label.pack(pady=20) # pady是上下邊距 # 啟動視窗(進入事件迴圈) window.mainloop() ``` --- ### 常用GUI元件 | 元件 | 用途 | 語法 | |------|------|------| | `Label` | 顯示文字或圖片 | `tk.Label(window, text="...")` | | `Button` | 可點擊的按鈕 | `tk.Button(window, text="...")` | | `Entry` | 單行輸入框 | `tk.Entry(window)` | | `Text` | 多行文字框 | `tk.Text(window)` | | `Frame` | 容器,組織元件 | `tk.Frame(window)` | | `Canvas` | 繪圖畫布 | `tk.Canvas(window)` | --- ### 加入按鈕互動 ```python import tkinter as tk def on_click(): """按鈕點擊事件""" label.config(text="按鈕被點擊了!✨") counter.set(counter.get() + 1) count_label.config(text=f"點擊次數:{counter.get()}") # 創建視窗 window = tk.Tk() window.title("互動程式 🎯") window.geometry("400x300") # 標籤 label = tk.Label(window, text="點擊下方按鈕", font=("Arial", 14)) label.pack(pady=20) # 計數器變數 counter = tk.IntVar(value=0) count_label = tk.Label(window, text="點擊次數:0", font=("Arial", 12)) count_label.pack(pady=10) # 按鈕 button = tk.Button(window, text="點我!", command=on_click, font=("Arial", 12), bg="lightblue", width=15, height=2) button.pack(pady=20) window.mainloop() ``` --- ### 輸入框與顯示 ```python import tkinter as tk def greet_user(): """處理使用者輸入""" name = entry.get() # 取得輸入內容 if name: result_label.config(text=f"哈囉,{name}!歡迎冒險!🎉") else: result_label.config(text="請輸入你的名字!", fg="red") # 創建視窗 window = tk.Tk() window.title("角色命名 ✏️") window.geometry("400x250") # 提示標籤 prompt_label = tk.Label(window, text="請輸入你的角色名稱:", font=("Arial", 12)) prompt_label.pack(pady=20) # 輸入框 entry = tk.Entry(window, font=("Arial", 12), width=30) entry.pack(pady=10) # 確認按鈕 button = tk.Button(window, text="確認", command=greet_user, font=("Arial", 11), bg="lightgreen", width=10) button.pack(pady=10) # 結果顯示標籤 result_label = tk.Label(window, text="", font=("Arial", 13), fg="blue") result_label.pack(pady=20) window.mainloop() ``` --- ### 完整範例:角色屬性面板 ```python import tkinter as tk class CharacterPanel: def __init__(self): self.window = tk.Tk() self.window.title("角色屬性面板 ⚔️") self.window.geometry("500x400") # 角色資料 self.hp = 100 self.mp = 50 self.level = 1 self.create_widgets() def create_widgets(self): """創建所有GUI元件""" # 標題 title = tk.Label(self.window, text="勇者屬性", font=("Arial", 18, "bold")) title.pack(pady=20) # 屬性顯示框架 info_frame = tk.Frame(self.window) info_frame.pack(pady=10) # HP標籤 self.hp_label = tk.Label(info_frame, text=f"❤️ HP: {self.hp}/100", font=("Arial", 14)) self.hp_label.grid(row=0, column=0, padx=20, pady=5) # MP標籤 self.mp_label = tk.Label(info_frame, text=f"💙 MP: {self.mp}/50", font=("Arial", 14)) self.mp_label.grid(row=1, column=0, padx=20, pady=5) # 等級標籤 self.level_label = tk.Label(info_frame, text=f"⭐ Level: {self.level}", font=("Arial", 14)) self.level_label.grid(row=2, column=0, padx=20, pady=5) # 按鈕框架 button_frame = tk.Frame(self.window) button_frame.pack(pady=30) # 治療按鈕 heal_btn = tk.Button(button_frame, text="治療 +20HP", command=self.heal, bg="lightgreen", width=12, font=("Arial", 10)) heal_btn.grid(row=0, column=0, padx=10) # 使用魔法按鈕 magic_btn = tk.Button(button_frame, text="魔法 -10MP", command=self.use_magic, bg="lightblue", width=12, font=("Arial", 10)) magic_btn.grid(row=0, column=1, padx=10) # 升級按鈕 levelup_btn = tk.Button(button_frame, text="升級", command=self.level_up, bg="gold", width=25, font=("Arial", 10)) levelup_btn.grid(row=1, column=0, columnspan=2, pady=10) def heal(self): """治療功能""" self.hp = min(100, self.hp + 20) self.update_display() def use_magic(self): """使用魔法""" if self.mp >= 10: self.mp -= 10 self.update_display() else: tk.messagebox.showwarning("MP不足", "魔法值不夠了!") def level_up(self): """角色升級""" self.level += 1 self.hp = 100 self.mp = 50 self.update_display() tk.messagebox.showinfo("升級", f"恭喜升到 Lv.{self.level}!") def update_display(self): """更新顯示""" self.hp_label.config(text=f"❤️ HP: {self.hp}/100") self.mp_label.config(text=f"💙 MP: {self.mp}/50") self.level_label.config(text=f"⭐ Level: {self.level}") def run(self): """執行程式""" self.window.mainloop() # 執行程式 if __name__ == "__main__": app = CharacterPanel() app.run() ```

--- ### 抽象化思維 (Abstraction) **從具體到抽象的過程:** ```python # 具體實作 hp = 100 mp = 50 name = "勇者" # ↓ 抽象化為函式 def create_character(name, hp, mp): return {"name": name, "hp": hp, "mp": mp} # ↓ 再抽象化為模組 # character_tools.py def create_character(name, job, level=1): """通用的角色創建函式""" stats = calculate_stats(job, level) return { "name": name, "job": job, "level": level, "hp": stats["hp"], "mp": stats["mp"] } ``` --- ### 介面設計思維 (Interface Design) **好的模組設計原則:** ```python # ✅ 好的設計:清晰的介面 import character_tools hero = character_tools.create_character("亞瑟", "騎士", 5) character_tools.show_status(hero) character_tools.level_up(hero) # ❌ 不好的設計:複雜的使用方式 hero = {"n": "亞瑟", "j": "騎士", "l": 5, "h": 500, "m": 250} print(f"名:{hero['n']} 職:{hero['j']} 級:{hero['l']}") hero['l'] += 1 hero['h'] = 100 * hero['l'] ``` **介面設計要點:** - 📝 **命名清楚**:函式名稱要一看就懂 - 📖 **文件完整**:加上docstring說明 - 🎯 **功能單一**:一個函式做好一件事 - 🔒 **減少參數**:參數越少越好用

--- ### GUI設計思維 (User Interface Thinking) **以使用者為中心的設計:** ``` 使用者體驗考量: ┌─────────────────────────────┐ │ 1. 直觀性 → 按鈕功能一目了然 │ │ 2. 回饋性 → 操作後有明確反應 │ │ 3. 容錯性 → 防呆設計,避免錯誤│ │ 4. 一致性 → 風格、邏輯要統一 │ └─────────────────────────────┘ ``` **範例:** ```python # ✅ 好的設計 def on_click(): result = process_data() if result: show_success_message() else: show_error_message("處理失敗,請檢查輸入") # ❌ 不好的設計 def on_click(): process_data() # 沒有回饋,使用者不知道是否成功 ```

✅ **GUI程式設計** - 建立視窗應用程式 - 處理使用者互動事件 - 設計友善的使用者介面

--- ### 模組化的威力 💪 **沒有模組化:** ```python # 所有程式碼都混在一起,難以維護 def main(): # 500行程式碼... # 角色、戰鬥、物品全部混在一起 pass ``` **有模組化:** ```python # 主程式:簡潔清晰 import character_tools import battle_system import item_manager def main(): hero = character_tools.create_character("勇者", "戰士") enemy = battle_system.spawn_enemy("哥布林") result = battle_system.fight(hero, enemy) if result == "win": item_manager.add_item(hero, "寶劍") ```

--- ### 從工具使用者到工具創造者 🛠️ ``` 第一階段:使用別人的工具 └─ import random, math, datetime 第二階段:組合現有工具 └─ 用matplotlib繪製圖表,用tkinter做介面 第三階段:創造自己的工具 ⭐ └─ 寫出自己的模組,分享給其他人使用 第四階段:工具生態系統 └─ 發布到PyPI,全世界都能用你的套件! ``` **你現在正處於第二到第三階段之間!** 🎉 --- ### 下週預告 🔮 **更進階的主題:** - 📂 檔案讀寫與資料處理 - 🐛 錯誤處理與除錯技巧 - 🎯 物件導向程式設計入門 - 🌐 網路爬蟲與API應用 **持續精進:** - 多寫自己的模組 - 嘗試更多視覺化專案 - 設計更多互動程式 - 閱讀別人的程式碼

--- ### 📝 **選項一:基礎練習** (適合初學者) #### 🎯 任務:打造個人化工具模組 **目標:** 建立一個 `my_tools.py` 模組,包含至少3個實用函式 **範例函式:** 1. **BMI計算器** ```python def calculate_bmi(weight, height): """計算BMI值並回傳健康建議""" pass ``` 2. **溫度轉換器** ```python def celsius_to_fahrenheit(celsius): """攝氏轉華氏""" pass def fahrenheit_to_celsius(fahrenheit): """華氏轉攝氏""" pass ``` 3. **密碼強度檢查** ```python def check_password_strength(password): """檢查密碼強度(長度、大小寫、數字、特殊字元)""" pass ``` **要求:** - ✅ 每個函式要有docstring說明 - ✅ 寫一個測試程式使用這些函式 - ✅ 加上適當的錯誤處理 --- ### 🔧 **選項二:進階應用** (有點挑戰性) #### 🎯 任務:成績管理系統 **目標:** 建立一個完整的成績管理系統,包含模組化設計和視覺化 **專案結構:** ``` grade_system/ ├── main.py # 主程式 ├── student_manager.py # 學生管理模組 ├── grade_calculator.py # 成績計算模組 ├── data_visualizer.py # 資料視覺化模組 └── gui_interface.py # GUI介面(選擇性) ``` **功能需求:** 1. **student_manager.py** - 新增學生資料 - 修改學生成績 - 刪除學生資料 - 查詢學生成績 2. **grade_calculator.py** - 計算平均分數 - 計算最高/最低分 - 統計及格/不及格人數 - 成績排名 3. **data_visualizer.py** - 繪製成績分布直方圖 - 繪製科目成績比較圖 - 繪製及格率圓餅圖 4. **main.py**(範例) ```python import student_manager as sm import grade_calculator as gc import data_visualizer as dv # 新增學生 sm.add_student("小明", {"國文": 85, "英文": 90, "數學": 78}) sm.add_student("小華", {"國文": 92, "英文": 88, "數學": 95}) # 計算統計 avg = gc.calculate_average() print(f"全班平均:{avg}") # 視覺化 dv.plot_grade_distribution() dv.plot_subject_comparison() ``` **額外挑戰:** - 🎨 加入Tkinter GUI介面 - 💾 資料持久化(存檔/讀檔) - 📊 更多視覺化圖表 --- ### 🚀 **選項三:創意發揮** (自由度高) #### 🎯 任務:創造你的專屬應用 **選擇一個你感興趣的主題,設計一個完整的應用程式!** **靈感來源:** 1. **🎮 小遊戲** - 猜數字遊戲(加入GUI和統計圖表) - 井字遊戲(Tic-Tac-Toe) - 打磚塊遊戲 2. **📊 資料分析工具** - 個人記帳本(支出分析圖表) - 健身追蹤器(體重/運動量記錄) - 學習時間統計工具 3. **🛠️ 實用工具** - 待辦事項管理器 - 簡易計算機(有GUI介面) - 檔案整理工具 4. **🎨 創意專案** - 隨機抽籤程式 - 問卷調查系統 - 簡易聊天機器人 **設計要求:** - ✅ 至少使用3個模組(可以自己寫或import) - ✅ 包含視覺化元素(圖表或GUI) - ✅ 程式碼要模組化、有註解 - ✅ 寫一份README.md說明如何使用 **範例專案結構:** ``` my_project/ ├── README.md # 專案說明 ├── main.py # 主程式 ├── core_functions.py # 核心功能模組 ├── ui_interface.py # 使用者介面 ├── data_handler.py # 資料處理 └── requirements.txt # 需要的套件 ``` --- ### 📤 繳交方式 **所有選項都需要:** 1. 📁 完整的程式碼檔案 2. 📸 執行結果截圖(至少3張) 3. 📝 簡短的心得報告(200字以上) - 你做了什麼? - 遇到什麼困難? - 學到了什麼? **截止日期:** 下週上課前 **加分項目:** - 🌟 程式碼註解完整 - 🌟 使用Git版本控制 - 🌟 設計精美的使用者介面 - 🌟 功能創新有創意