返回目录

最简短的UI控制开关灯.py PY

text/plain
1.09 KB
2026-01-18 12:10:38
下载文件

文件预览

语言: python | 编码: UTF-8
总行数: 39
import tkinter as tk
import serial

root = tk.Tk()            # 创建主窗口
root.title("灯光控制")
root.geometry("200x200")
serial_port = serial.Serial('COM3', 9600, timeout=1)   # 创建串口对象

def turn_light_on():
    """开灯 - 发送字符 '1'"""
    if serial_port and serial_port.is_open:
        serial_port.write(b'1')
        print("已发送: 1 (开灯)")

def turn_light_off():
    """关灯 - 发送字符 '2'"""
    if serial_port and serial_port.is_open:
        serial_port.write(b'2')
        print("已发送: 2 (关灯)")

def on_closing():
    """关闭窗口时关闭串口"""
    if serial_port and serial_port.is_open:
        serial_port.close()
        print("串口已关闭")
    root.destroy()

# 创建按钮
btn_on = tk.Button(root, text="开灯", command=turn_light_on, bg="green", fg="white", width=15, height=3)
btn_on.pack(pady=10)

btn_off = tk.Button(root, text="关灯", command=turn_light_off, bg="red", fg="white", width=15, height=3)
btn_off.pack(pady=10)

# 绑定关闭事件
root.protocol("WM_DELETE_WINDOW", on_closing)

# 运行主循环
root.mainloop()