此代码为红绿灯系统,将其改正为可视化效果,能让用户直观感受出各种颜色的变化
时间: 2024-03-11 22:47:18 浏览: 15
要实现红绿灯系统的可视化效果,可以使用Python中的GUI库来构建一个简单的UI界面。这里我们使用Tkinter库来创建一个窗口,然后在窗口中添加三个Label控件来模拟红绿灯的状态。
下面是示例代码:
```python
import RPi.GPIO as GPIO
import time
import tkinter as tk
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
RED = 18
YELLOW = 27
GREEN = 22
GPIO.setup(RED, GPIO.OUT)
GPIO.setup(YELLOW, GPIO.OUT)
GPIO.setup(GREEN, GPIO.OUT)
def red_light():
GPIO.output(RED, GPIO.HIGH)
GPIO.output(YELLOW, GPIO.LOW)
GPIO.output(GREEN, GPIO.LOW)
def yellow_light():
GPIO.output(RED, GPIO.LOW)
GPIO.output(YELLOW, GPIO.HIGH)
GPIO.output(GREEN, GPIO.LOW)
def green_light():
GPIO.output(RED, GPIO.LOW)
GPIO.output(YELLOW, GPIO.LOW)
GPIO.output(GREEN, GPIO.HIGH)
def update_light():
while True:
red_light()
time.sleep(5)
yellow_light()
time.sleep(2)
green_light()
time.sleep(5)
def create_window():
window = tk.Tk()
window.title("Traffic Light")
window.geometry('150x300')
red_label = tk.Label(window, bg='black', width=10, height=5)
red_label.grid(column=0, row=0)
yellow_label = tk.Label(window, bg='black', width=10, height=5)
yellow_label.grid(column=0, row=1)
green_label = tk.Label(window, bg='black', width=10, height=5)
green_label.grid(column=0, row=2)
return window, red_label, yellow_label, green_label
def update_ui(red_label, yellow_label, green_label):
while True:
red_label.config(bg='red')
time.sleep(5)
yellow_label.config(bg='yellow')
time.sleep(2)
green_label.config(bg='green')
time.sleep(5)
if __name__ == '__main__':
window, red_label, yellow_label, green_label = create_window()
update_ui_thread = threading.Thread(target=update_ui, args=(red_label, yellow_label, green_label))
update_ui_thread.start()
update_light_thread = threading.Thread(target=update_light)
update_light_thread.start()
window.mainloop()
GPIO.cleanup()
```
这段代码首先定义了一个红绿灯控制函数,然后使用Tkinter库创建了一个窗口,并在窗口中添加了三个Label控件来模拟红绿灯的状态。接着,我们使用两个线程来分别更新红绿灯状态和UI界面,最后启动主循环,等待窗口关闭。