安裝
使用 pip 安裝 Python QR碼函式庫。
pip
pip install qrcode[pil]pip (segno)
pip install segno使用 Python 函式庫產生 QR碼
使用熱門 Python QR碼函式庫的程式碼範例。
Basic QR Code with qrcode
import qrcode
# Simple generation
img = qrcode.make('https://qrcode.fun')
img.save('qrcode.png')
# Advanced with customization
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data('https://qrcode.fun')
qr.make(fit=True)
img = qr.make_image(fill_color='#1A2B3C', back_color='white')
img.save('qrcode_custom.png')SVG Output with segno
import segno
qr = segno.make('https://qrcode.fun')
qr.save('qrcode.svg', scale=10)
qr.save('qrcode.png', scale=10, dark='#1A2B3C')QR Code with Logo
import qrcode
from PIL import Image
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)
qr.add_data('https://qrcode.fun')
qr.make(fit=True)
img = qr.make_image(fill_color='#1A2B3C', back_color='white').convert('RGB')
# Add logo
logo = Image.open('logo.png')
logo_size = img.size[0] // 4
logo = logo.resize((logo_size, logo_size))
pos = ((img.size[0] - logo_size) // 2, (img.size[1] - logo_size) // 2)
img.paste(logo, pos)
img.save('qrcode_logo.png')QRCode.fun API
透過 API 在 Python 中產生 QR碼
從 Python 呼叫 QRCode.fun API,產生帶有自訂顏色、形狀和標誌的樣式化 QR碼。
Python API 整合
import requests
response = requests.post('https://qrcode.fun/api/generate-qr-styled', json={
'data': 'https://qrcode.fun',
'width': 300,
'height': 300,
'type': 'png',
'margin': 10,
'dotsOptions': {
'color': '#1A2B3C',
'type': 'rounded'
},
'cornersSquareOptions': {
'color': '#8564C3',
'type': 'extra-rounded'
},
'backgroundOptions': {
'color': '#FFFFFF'
}
})
result = response.json()
# result['data'] contains the base64 PNG data URL
print(result['data'][:50])即時 QR碼預覽
立即嘗試使用 Python 產生 QR碼。
QR碼預覽
原生函式庫 vs API
比較直接使用 Python QR碼函式庫與 QRCode.fun API。
| 功能 | 原生函式庫 | QRCode.fun API |
|---|---|---|
| 設定複雜度 | pip install + Pillow 用於影像 | 透過 requests 發送單次 HTTP 請求 |
| 自訂 | 顏色、糾錯等級、方塊大小 | 完整樣式:顏色、形狀、標誌 |
| 離線支援 | 是 | 需要網路 |
| 維護 | 手動更新套件 | 始終保持最新 |
| 輸出格式 | PNG, SVG, EPS, 終端機 | PNG, SVG |
Python QR碼使用情境
Python 開發者產生 QR碼的常見情境。
資料科學與報告
在自動化報告、Jupyter notebook 和資料視覺化中嵌入 QR碼,連結到儀表板或資料集。
Web 應用(Django/Flask)
在 Django 或 Flask 應用中伺服器端產生 QR碼,用於使用者資料、票券和身份驗證權杖。
自動化腳本
在批次處理腳本中建立 QR碼,用於庫存標籤、資產追蹤和文件管理。
IoT 與 Raspberry Pi
在嵌入式裝置上產生 QR碼,用於 Wi-Fi 設定、裝置配對和設定共享。
常見問題
關於使用 Python 產生 QR碼的常見問題。
qrcode 函式庫是最受歡迎的選擇——它簡單、維護良好,並支援 Pillow 進行影像輸出。segno 是一個很好的替代方案,提供 SVG 輸出和更精簡的程式碼。