萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python Tkinter 顯示網路圖片:urllib + PIL + BytesIO 完整實作

技術棧

  • tkinter:Python 內建 GUI 框架
  • PIL/Pillow:影像處理,支援多種格式 (非僅 GIF)
  • io.BytesIO:記憶體位元組串流,避免落地暫存檔
  • urllib:網路請求 (Python 3 為 urllib.request)

完整跨版本程式碼


import io
import sys
from PIL import Image, ImageTk

# 相容 Python 2/3
if sys.version_info[0] == 2:
    import Tkinter as tk
    from urllib2 import urlopen
else:
    import tkinter as tk
    from urllib.request import urlopen

def show_image_from_url(url, title="Image Viewer"):
    root = tk.Tk()
    root.title(title)
    
    try:
        # 下載圖片位元組
        with urlopen(url) as resp:
            image_bytes = resp.read()
        
        # 位元組串流 -> PIL Image
        data_stream = io.BytesIO(image_bytes)
        pil_image = Image.open(data_stream)
        
        # 顯示圖片資訊
        w, h = pil_image.size
        fname = url.split('/')[-1]
        root.title(f"{fname} ({w}x{h})")
        
        # PIL Image -> Tkinter PhotoImage
        tk_image = ImageTk.PhotoImage(pil_image)
        
        # 顯示於 Label
        label = tk.Label(root, image=tk_image, bg='gray')
        label.image = tk_image  # 保持引用,防止 GC 回收導致圖片消失
        label.pack(padx=10, pady=10)
        
    except Exception as e:
        tk.Label(root, text=f"載入失敗: {e}", fg='red').pack(padx=10, pady=10)
    
    root.mainloop()

if __name__ == '__main__':
    # 測試圖片
    test_url = "https://httpbin.org/image/jpeg"
    show_image_from_url(test_url)

關鍵陷阱:PhotoImage 被 GC 回收

必須保持對 tk_image 的引用 (如 label.image = tk_image),否則函式結束時區域變數釋放,Tkinter 顯示空白。

進階:非同步下載避免界面凍結


import threading

def async_show_image(url, label, root):
    def worker():
        try:
            with urlopen(url) as resp:
                data = resp.read()
            pil_img = Image.open(io.BytesIO(data))
            tk_img = ImageTk.PhotoImage(pil_img)
            # 回主線程更新 UI
            root.after(0, lambda: update_label(label, tk_img, url))
        except Exception as e:
            root.after(0, lambda: label.config(text=f"錯誤: {e}", image=''))
    
    def update_label(lbl, img, url):
        lbl.config(image=img, text='')
        lbl.image = img
        root.title(f"{url.split('/')[-1]} ({img.width()}x{img.height()})")
    
    threading.Thread(target=worker, daemon=True).start()

# 在主程式中
label = tk.Label(root, text="載入中...")
label.pack()
async_show_image(url, label, root)

生產建議

  • 大型應用考慮 customtkinter、PyQt、PySide 等現代 GUI 框架。
  • 圖片快取:避免重複下載相同 URL。
  • 錯誤處理:超時、無效圖片格式、網路中斷。
copyright © 萬盛學電腦網 all rights reserved