Python GUI 与硬件交互:Tkinter 控制树莓派 LED 灯

硬件接线图说明
树莓派 GPIO 引脚 ───[电阻]─── LED正极(长脚)
树莓派 GND 引脚 ───────────── LED负极(短脚)

关键参数

  • 电阻值:$220 \Omega \sim 1k\Omega$(推荐$330\Omega$)
  • 推荐GPIO引脚:GPIO17(物理引脚11)
  • GND引脚:任意接地引脚(如物理引脚9)
Python 实现代码
import RPi.GPIO as GPIO
import tkinter as tk

# 初始化GPIO
LED_PIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT, initial=GPIO.LOW)

def toggle_led():
    """切换LED状态"""
    current_state = GPIO.input(LED_PIN)
    GPIO.output(LED_PIN, not current_state)
    status_label.config(text="LED: ON" if not current_state else "LED: OFF")

def on_closing():
    """关闭窗口时清理资源"""
    GPIO.cleanup()
    window.destroy()

# 创建GUI窗口
window = tk.Tk()
window.title("树莓派LED控制")
window.geometry("300x150")
window.protocol("WM_DELETE_WINDOW", on_closing)

# 控制按钮
control_btn = tk.Button(window, 
                        text="切换LED", 
                        command=toggle_led,
                        height=2, 
                        width=15)
control_btn.pack(pady=20)

# 状态标签
status_label = tk.Label(window, 
                        text="LED: OFF", 
                        font=("Arial", 14))
status_label.pack()

window.mainloop()

操作步骤
  1. 硬件连接

    • 将电阻一端连接GPIO17(物理引脚11)
    • 电阻另一端连接LED正极(长脚)
    • LED负极(短脚)连接任意GND引脚
  2. 软件配置

    # 安装依赖库
    sudo apt-get install python3-tk
    pip install RPi.GPIO
    

  3. 运行程序

    python3 led_control.py
    

原理解析
  1. GPIO控制

    • 使用GPIO.output()函数控制引脚电压
    • 高电平($3.3V$)点亮LED,低电平($0V$)熄灭
  2. Tkinter交互

    • 按钮绑定command回调函数
    • 状态标签实时显示LED状态
  3. 电流保护

    • 电阻限制电流在安全范围
    • 最大电流计算:$I_{max} = \frac{3.3V}{330\Omega} \approx 10mA$

注意事项

  1. 务必断开电源接线
  2. 避免GPIO引脚直接短路
  3. 使用GPIO.cleanup()防止引脚状态残留
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐