iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0
Software Development

從零開始學 Python系列 第 27

Day 27 – 初學 GUI:用 tkinter 建立小視窗程式

  • 分享至 

  • xImage
  •  

今天的學習重點

  • 什麼是 GUI(Graphical User Interface)
  • Python 的內建 GUI 工具:tkinter
  • 建立一個簡單視窗
  • 加入標籤(Label)、按鈕(Button)、輸入框(Entry)
  • 小小互動範例:按下按鈕顯示文字

什麼是 GUI?

GUI(Graphical User Interface,圖形使用者介面)就是讓程式可以透過「視覺化的方式」和使用者互動,而不是只在黑底的終端機輸入指令。
常見的 GUI 元件包括:

  • 視窗 (Window) → 程式的主要框架
  • 標籤 (Label)
  • 輸入框 (Entry / Text)
  • 按鈕 (Button)
  • 下拉選單、核取方塊、選項按鈕

在 Python 裡,最常見的 GUI 工具就是 tkinter(內建,不需要額外安裝)

建立一個簡單視窗

import tkinter as tk

# 建立主視窗
window = tk.Tk()
window.title("GUIGUI")
window.geometry("300x200")  # 設定視窗大小

# 啟動 GUI 事件迴圈
window.mainloop()

執行後會跳出一個小視窗。
螢幕擷取畫面 2025-08-29 143630

加入標籤、按鈕與輸入框

import tkinter as tk

def say_hello():
    user_name = entry.get()  # 讀取輸入框文字
    label.config(text=f"Hello, {user_name}!")

# 視窗
window = tk.Tk()
window.title("GUIGUI")
window.geometry("300x200")

# 標籤
label = tk.Label(window, text="輸入名字:")
label.pack(pady=10)

# 輸入框
entry = tk.Entry(window)
entry.pack()

# 按鈕
button = tk.Button(window, text="打招呼", command=say_hello)
button.pack(pady=10)

window.mainloop()

螢幕擷取畫面 2025-08-29 143821

  • Label → 顯示文字
  • Entry → 使用者輸入文字
  • Button → 按鈕,點擊後呼叫一個函式
  • pack() → 一種版面配置方式,把元件一個個疊上去

exercise:小計算機

試著把 GUI 與簡單運算結合,做一個加法小工具:

import tkinter as tk

def calculate():
    try:
        num1 = float(entry1.get())
        num2 = float(entry2.get())
        result = num1 + num2
        label_result.config(text=f"結果:{result}")
    except ValueError:
        label_result.config(text="請輸入數字!")

window = tk.Tk()
window.title("小計算機")
window.geometry("300x200")

tk.Label(window, text="數字 1:").pack()
entry1 = tk.Entry(window)
entry1.pack()

tk.Label(window, text="數字 2:").pack()
entry2 = tk.Entry(window)
entry2.pack()

button = tk.Button(window, text="加總", command=calculate)
button.pack(pady=10)

label_result = tk.Label(window, text="結果:")
label_result.pack()
window.mainloop()

螢幕擷取畫面 2025-08-29 144116

學習心得

明天要進行綜合練習:把 requests + BeautifulSoup + tkinter 結合,做一個「小爬蟲 GUI 工具」。
流程會是:輸入網址 → 抓標題 → 顯示在 GUI 介面裡。


上一篇
Day 26 – BeautifulSoup 初探:抓取網頁標題
下一篇
Day 28 – 綜合練習:爬蟲 + GUI 小工具
系列文
從零開始學 Python30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言