본문 바로가기

코딩/파이썬 kivy

kivy 스터디 009. 클럭 이벤트 (clock events) 1 - schedule_once()

kivy : events : clock events

kivy 이벤트

kivy 프로그램은 이벤트에 의해 프로그램의 실행이 결정되는데, kivy에선 이를 event-based라고 설명한다.

 

getting started에서 소개하는 kivy 이벤트의 종류는 3가지 이다.

 

  • Clock events
  • Input events
  • Class events

kivy에서 이벤트의 처리 흐름을 도식화하면 아래와 같다.

 

events in the kivy framework

Clock 이벤트

getting started에서 설명하는 클럭 이벤트에는 아래와 같은 이벤트들이 있다.

 

  • One-time event with schedule_once()
  • Repetitive event with schedule_interval()
  • Triggered events with create_trigger()

클럭 이벤트 (clock events) 1 - schedule_once()

메서드 schedule_once는 schedule_once 메서드를 호출한 이후 설정한 callback 메서드 또는 함수를 한번만 실행시키고자 할 때 사용한다.

 

메서드 schedule_once는 클래스 CyClockBase 내에 정의되어 있는 메서드이다.

 

def schedule_once(self, callback, timeout=0)

 

다음의 코드는 화면 좌, 우 버튼을 표시하는 애플리케이션을 구현하는 코드로

 

schedule_once 메서드를 사용하는 애플리케이션

 

클래스 MyApp 내 메서드 build에서 schedule_once 메서드를 호출하여 호출 시점으로부터 1초 후에 메서드 my_clock_callback이 실행된다.

 

import kivy
kivy.require('2.0.0')

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.clock import Clock

class ScreenLayout(GridLayout):
    def __init__(self, **kwargs):
        GridLayout.__init__(self, **kwargs)
        self.cols = 2
        self.button1 = Button(text='Button 1')
        self.add_widget(self.button1)
        self.button2 = Button(text='Button 2')
        self.add_widget(self.button2)

class MyApp(App):
    def build(self):
        self.clock_event = Clock.schedule_once(self.my_clock_callback, 1.)
        return ScreenLayout()

    def my_clock_callback(self, dt):
        print('my clock callback', dt)

if __name__ == '__main__':
    MyApp().run()

 

위의 코드를 실행하면, 파이참 출력창에 my clock callback x.xxx문구가 표시된다.

 

schedule_once 메서드에 의한 callback 메서드 실행

 

메서드 schedule_once를 호출한 이후 설정한 callback 메서드 또는 함수가 실행되기 전

아래과 같이 cancel 메서드를 호출하면, 설정한 callback 메서드 또는 함수는 실행되지 않는다.

 

    def build(self):
        self.clock_event = Clock.schedule_once(self.my_clock_callback, 1.)
        # -----------------------------
        print(type(self.clock_event))
        self.clock_event.cancel()
        # -----------------------------
        return ScreenLayout()

 

schedule_once 메서드 호출로 생성된 객체의 타입은 ClockEvent이다.

 

<class 'kivy._clock.ClockEvent'>