如何使LED闪烁并同时更改形状的填充颜色?

时间:2019-05-03 23:37:43

标签: python-3.x function tkinter gpiozero

我正在编写带电转向灯的代码。

我可以使LED闪烁,也可以使多边形更改其填充颜色以模拟转向信号。

这对领导者有用:

def blink_arrow():
    leftBlinker.blink(on_time=.7, off_time=.3, n=3)

这适用于形状填充:

def blink_arrow(count=0):
    global arrow_color
    global left_arrow
    if arrow_color == "green":
        left_arrow = c.create_polygon(50, 100, 150, 75, 150, 125, fill="gray")
    elif arrow_color == "gray":
        left_arrow = c.create_polygon(50, 100, 150, 75, 150, 125, fill="green")

    if count <5:
        w.after(300 if left_arrow=="green" else 700, blink_arrow, count+1)

这是我尝试的方法,但是没有用:

from tkinter import Canvas
from gpiozero import Button, LED

button = Button(23)
leftBlinker = LED(17)

def blink_arrow(count=0):
    leftBlinker.blink(on_time=.7, off_time=.3, n=1)
    global arrow_color
    global left_arrow
    if arrow_color == "green":
        left_arrow = c.create_polygon(50, 100, 150, 75, 150, 125, fill="gray")
    elif arrow_color == "gray":
        left_arrow = c.create_polygon(50, 100, 150, 75, 150, 125, fill="green")

    if count <5:
        w.after(300 if left_arrow=="green" else 700, blink_arrow, count+1)

#Build window, canvas, shape 

button.when_pressed = blink_arrow

这里是您建议的新代码:

def blink_arrow(count=0)
    #code for function as written in my first example
    pass

def blink_leftLED():
    leftBlinker.blink(on_time=.7, off_time=.3, 3)
    pass

def left_signal():
    l1 = Thread(blink_arrow)
    l2 = Thread(blink_leftLED)
    l1.start()
    l2.start()

left_button.when_pressed = left_signal

这是错误:

...line 28 in left_signal
l1 = Thread(blink_arrow)
...line reference to threading.py...
assert group is None, "group argument must be none for now"

请帮助。 :)

我希望多边形和LED同步“闪烁”。我可以使用谨慎的功能使它们单独闪烁,但不能一起闪烁。如上所述,当我尝试在一个函数中同时调用两者时,指示灯会亮起,并且填充颜色会更改一次。

2 个答案:

答案 0 :(得分:0)

使两个函数同时运行的最有效方法可能是使用threading或多处理模块。线程是预安装的,通常用于多处理,这似乎是您在这里想要做的(并行运行两个功能)。这是一个示例:

from threading import Thread

#rest of code

def function2():
   pass
def function1():
   pass

t1 = Thread(group=None,target=function1)
t2 = Thread(group=None,target=function2)
t1.start()
t2.start()

或者,通过按钮调用事件:

from gpiozero import Button, LED    
from threading import Thread

#rest of code

def function2():
   pass
def function1():
   pass

def main_functions():
   t1 = Thread(group=None,target=function1)
   t2 = Thread(group=None,target=function2)
   t1.start()
   t2.start()
button.when_pressed = main_functions

这些只是一些示例。

请注意,线程中的'function1'或'function2'目标后面没有括号(很容易遗漏,然后代码将不起作用)。我希望这会有所帮助!

答案 1 :(得分:0)

您可以使用.after(...)而不是使用线程来简单地打开/关闭相同功能内的LED和箭头:

def left_signal(count=0, arrow_color='green'):
    blink_on = arrow_color == 'green'
    if blink_on:
        leftBlinker.on()
    else:
        leftBlinker.off()
    c.itemconfig(left_arrow, fill=arrow_color)
    if count < 5:
        w.after(300 if blink_on else 700, left_signal, count+1, 'gray' if blink_on else 'green')