0

我使用 tkinter 创建了 GUI,它将在 RaspberryPi 上运行并执行各种操作,例如点亮 LED。我遇到的问题是使用 root 来打开和关闭 LED。在调度之后,就像我使用 time.sleep() 一样,GUI 将在此睡眠时冻结。这是我的代码,下面我想用大约 500 毫秒的某种延迟替换 time.sleep()。

def toggleLED(root,period=0):
    if (period <15) and (Status is "On"):
            GPIO.output(11, True)
            time.sleep(0.5) #Needs to be replaced as causing GUI to freeze
            GPIO.output(11, False)
            root.after(1000, lambda: toggleLED(root, period)) #schedule task every 1 second while condition is true
    elif (Status == "Off"):
            print("Lights have been switched off")
    else:
            GPIO.output(11, True)

谢谢

这是一种解决方案,但看起来很混乱:

def toggleLED(root,period=0):
    global Flash
    while (period <30) and (Status is "On"):
            if (Flash is True):
                    GPIO.output(11, False)
                    Flash = False
                    break
            elif (Flash is False):
                    GPIO.output(11, True)
                    Flash = True
                    break
            else:
                    break
    if (period <30) and (Status == "On"):
            period +=1
            print(period)
            root.after(500, lambda: toggleLED(root, period))
    elif (Status == "Off"):
           print("Lights have been switched off")
    else:
           GPIO.output(11, True)
4

1 回答 1

1

问题的一部分是你的while循环——你不需要任何类型的循环,因为你有事件循环。

下面是一个每 500 毫秒切换标签 30 秒的示例:

import Tkinter as tk

class Example(tk.Frame):

    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self._job_id = None

        self.led = tk.Label(self, width=1, borderwidth=2, relief="groove")
        self.start_button = tk.Button(self, text="start", command=self.start)
        self.stop_button = tk.Button(self, text="stop", command=self.stop)

        self.start_button.pack(side="top")
        self.stop_button.pack(side="top")
        self.led.pack(side="top")

    def stop(self):
        if self._job_id is not None:
            self.after_cancel(self._job_id)
            self._job_id = None
            self.led.configure(background="#ffffff")

    def start(self):
        self._job_id = self.after(500, lambda: self.toggle(60))

    def toggle(self, counter):
        bg = self.led.cget("background")
        bg = "#ffffff" if bg == "#ff0000" else "#ff0000"
        self.led.configure(background=bg)
        if counter > 1:
            self._job_id = self.after(500, lambda: self.toggle(counter-1))

root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
于 2013-05-18T22:09:16.897 回答