文章字數統計器

from io import BytesIO

import customtkinter as ctk
import requests
from PIL import Image


### 基本視窗設定
ctk.set_appearance_mode("dark") # 設定外觀模式為深色模式
ctk.set_default_color_theme("blue") # 設定 CustomTkinter 預設主題顏色為藍色

window = ctk.CTk() # 建立 CustomTkinter 主視窗
window.title("文章字數統計器") # 設定視窗標題
window.geometry("620x850") # 設定視窗大小,寬 620、高 850


### 下載圖片
image_url = "https://i.pinimg.com/736x/89/e5/26/89e526d0bc6e3a66606ac709cfb53bfe.jpg" # 設定網路圖片網址

response = requests.get(image_url) # 從指定網址下載圖片
image_data = BytesIO(response.content) # 將下載的二進位圖片資料轉成記憶體檔案
image = Image.open(image_data) # 使用 PIL 開啟圖片
image = image.resize((280, 180)) # 將圖片調整為寬 280、高 180


### 轉成 CTkImage
ctk_image = ctk.CTkImage(
    light_image=image, # Light 模式使用的圖片
    dark_image=image, # Dark 模式使用的圖片
    size=(280, 180) # 設定圖片顯示大小,寬 280、高 180
)


### 統計文章函式
def count_text():
    text = textbox.get("1.0", "end-1c") # 取得 Textbox 從第一個字元到最後一個字元的內容

    char_count = len(text) # 計算文章總字元數
    line_count = len(text.splitlines()) # 將文字依照換行切開,再計算總行數

    result_label.configure(
        text=f"統計結果\n字元數:{char_count} 行數:{line_count}" # 更新 Label 顯示統計結果
    )


### 建立標題 Label
title_label = ctk.CTkLabel(
    window, # 指定 Label 放在主視窗 window 裡面
    text="文章字數統計器", # 設定 Label 顯示的文字
    font=("Microsoft JhengHei", 30, "bold") # 設定字型、字體大小與粗體
)

title_label.pack(pady=(20, 10)) # 上方增加 20、下方增加 10 像素的間距


### 建立圖片 Label
image_label = ctk.CTkLabel(
    window, # 指定 Label 放在主視窗 window 裡面
    text="", # 清空文字,只顯示圖片
    image=ctk_image # 設定 Label 顯示的圖片
)

image_label.pack(pady=10) # 將圖片 Label 放入視窗


### 建立說明 Label
hint_label = ctk.CTkLabel(
    window, # 指定 Label 放在主視窗 window 裡面
    text="請在下方輸入或貼上文章內容", # 顯示操作提示文字
    font=("Microsoft JhengHei", 18) # 設定字型與字體大小
)

hint_label.pack(pady=10) # 將說明 Label 放入視窗


### 建立 Textbox
textbox = ctk.CTkTextbox(
    window, # 指定 Textbox 放在主視窗 window 裡面
    width=520, # 設定文字輸入區寬度
    height=250, # 設定文字輸入區高度
    font=("Microsoft JhengHei", 18), # 設定字型與字體大小
    wrap="word" # 文字超過寬度時,以完整單字為單位自動換行
)

textbox.pack(pady=10) # 將 Textbox 放入視窗


### 建立結果 Label
result_label = ctk.CTkLabel(
    window, # 指定 Label 放在主視窗 window 裡面
    text="尚未統計", # 設定尚未統計時的預設文字
    font=("Microsoft JhengHei", 22, "bold"), # 設定字型、字體大小與粗體
    justify="center" # 設定多行文字置中對齊
)

result_label.pack(pady=15) # 將結果 Label 放入視窗


### 建立統計按鈕
count_button = ctk.CTkButton(
    window, # 指定 Button 放在主視窗 window 裡面
    text="開始統計", # 設定按鈕顯示的文字
    font=("Microsoft JhengHei", 20, "bold"), # 設定字型、字體大小與粗體
    width=220, # 設定按鈕寬度
    height=50, # 設定按鈕高度
    command=count_text # 按下按鈕時執行 count_text 函式
)

count_button.pack(pady=10) # 將按鈕放入視窗


### 啟動視窗
window.mainloop() # 啟動事件迴圈,讓視窗持續顯示並等待使用者操作