2013-03-25 4 views
0

나는 Tkinter를 사용하여 GUI를 만들었다. tkinter는 RaspberryPi에서 실행되며 조명 LED와 같은 다양한 동작을 수행 할 것이다. 내가 가진 문제는 root.after 일정을 사용하여 LED를 켜고 끄는 것인데, 마치 time.sleep()을 사용하는 것처럼이 수면 상태에서 GUI가 멈 춥니 다. 다음은 내 코드입니다. 아래에 time.sleep()을 약 500ms의 지연으로 대체하려고합니다.tkinter로 지연을 사용하는 파이썬 조언

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) 
+0

귀하의 솔루션은 중복 코드 및 불필요한 블록을 제거하여 세척 할 수 있습니다. 그러나 달성하고자하는 결과는 무엇입니까? 빛을 30 번 토글하고 있니? –

+0

예, 표시등은 15 초 이내에 30 번 토글해야합니다. – user2207573

답변

1

부분은 당신의 while 루프 - 당신은 루프의 모든 종류의 이후 필요하지 않습니다 이벤트 루프가 있습니다.

여기에 30 초 동안 레이블마다 500ms 이내 전환의 예 :

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()