5.13. 간단한 TUI 스포크 정의


다음 예제에서는 Hello World 샘플 애드온에서 제공하는 간단한 텍스트 사용자 인터페이스(TUI) 구현을 보여줍니다.

사전 요구 사항

프로세스

  • 다음 예에 따라 모든 필수 정의로 모듈을 생성하여 추가 기능 텍스트 사용자 인터페이스(TUI)에 대한 지원을 추가합니다.

예 5.5. 간단한 TUI 스포크 정의

class HelloWorldSpoke(NormalTUISpoke):
    # category this spoke belongs to
    category = HelloWorldCategory

def __init__(self, *args, **kwargs):
    """
    Create the representation of the spoke.

    :see: simpleline.render.screen.UIScreen
    """
    super().__init__(*args, **kwargs)
    self.title = N_("Hello World")
    self._hello_world_module = HELLO_WORLD.get_proxy()
    self._container = None
    self._reverse = False
    self._lines = ""

def initialize(self):
    """
    The initialize method that is called after the instance is created.
    The difference between __init__ and this method is that this may take
    a long time and thus could be called in a separated thread.

    :see: pyanaconda.ui.common.UIObject.initialize
    """
    # nothing to do here
    super().initialize()

def setup(self, args=None):
    """
    The setup method that is called right before the spoke is entered.
    It should update its state according to the contents of DBus modules.

    :see: simpleline.render.screen.UIScreen.setup
    """
    super().setup(args)

    self._reverse = self._hello_world_module.Reverse
    self._lines = self._hello_world_module.Lines

    return True

def refresh(self, args=None):
    """
    The refresh method that is called every time the spoke is displayed.
    It should generate the UI elements according to its state.

    :see: pyanaconda.ui.common.UIObject.refresh
    :see: simpleline.render.screen.UIScreen.refresh
    """
    super().refresh(args)

    self._container = ListColumnContainer(
        columns=1
    )
    self._container.add(
        CheckboxWidget(
            title="Reverse",
            completed=self._reverse
        ),
        callback=self._change_reverse
    )
    self._container.add(
        EntryWidget(
            title="Hello world text",
            value="".join(self._lines)
        ),
        callback=self._change_lines
    )

    self.window.add_with_separator(self._container)

def _change_reverse(self, data):
    """
    Callback when user wants to switch checkbox.
    Flip state of the "reverse" parameter which is boolean.
    """
    self._reverse = not self._reverse

def _change_lines(self, data):
    """
    Callback when user wants to input new lines.
    Show a dialog and save the provided lines.
    """
    dialog = Dialog("Lines")
    result = dialog.run()
    self._lines = result.splitlines(True)

def input(self, args, key):
    """
    The input method that is called by the main loop on user's input.

    * If the input should not be handled here, return it.
    * If the input is invalid, return InputState.DISCARDED.
    * If the input is handled and the current screen should be refreshed,
      return InputState.PROCESSED_AND_REDRAW.
    * If the input is handled and the current screen should be closed,
      return InputState.PROCESSED_AND_CLOSE.

    :see: simpleline.render.screen.UIScreen.input
    """
    if self._container.process_user_input(key):
        return InputState.PROCESSED_AND_REDRAW

    if key.lower() == Prompt.CONTINUE:
        self.apply()
        self.execute()
        return InputState.PROCESSED_AND_CLOSE

    return super().input(args, key)

def apply(self):
    """
    The apply method is not called automatically for TUI. It should be called
    in input() if required. It should update the contents of internal data
    structures with values set in the spoke.
    """
    self._hello_world_module.SetReverse(self._reverse)
    self._hello_world_module.SetLines(self._lines)

def execute(self):
    """
    The execute method is not called automatically for TUI. It should be called
    in input() if required. It is supposed to do all changes to the runtime
    environment according to the values set in the spoke.
    """
    # nothing to do here
    pass
Copy to Clipboard Toggle word wrap

자세한 내용 및 최신 코드는 Hello World Anaconda 애드온 - GitHub 리포지토리 를 참조하십시오.

참고

ancestor의 init 만 호출하는 경우 init 메서드를 재정의할 필요는 없지만 예제의 주석은 이해할 수 있는 방식으로 spoke 클래스의 생성자에 전달된 인수를 설명합니다.

이전 예에서 다음을 수행합니다.

  • setup 메서드는 모든 항목에 대해 spoke의 내부 특성에 대한 기본값을 설정합니다. 이 값은 새로 고침 메서드에서 표시한 후 입력 방법으로 업데이트하고 apply 메서드에서 내부 데이터 구조를 업데이트하는 데 사용합니다.
  • 실행 방법은 GUI에서 동일한 방법과 동일한 목적을 갖습니다. 이 경우 메서드는 적용되지 않습니다.
  • 입력 방법은 텍스트 인터페이스에 고유합니다. Kickstart 또는 GUI에는 동등한 항목이 없습니다. 입력 방법은 사용자 상호 작용에 대한 책임이 있습니다.
  • 입력 방법은 입력된 문자열을 처리하고 해당 유형과 값에 따라 작업을 수행합니다. 위의 예제에서는 모든 값을 요청한 다음 내부 속성(키)으로 저장합니다. 더 복잡한 추가 기능에서는 일반적으로 작업과 같이 구문 분석 문자, 숫자를 정수로 변환하고, 추가 화면을 표시하거나 부울 값을 토글하는 것과 같은 몇 가지 중요하지 않은 작업을 수행해야 합니다.
  • 입력 클래스의 반환 값은 InputState enum 또는 입력 문자열 자체여야 합니다.If this input class should be processed by a different screen. 그래픽 모드와 달리, spoke를 벗어나면 applyexecute 방법이 자동으로 호출되지 않습니다. 입력 방법에서 명시적으로 호출해야 합니다. 대화 상자의 화면을 닫는 데도 동일하게 적용됩니다. 가까운 방법에서 명시적으로 호출해야 합니다.

예를 들어 다른 대화 상자에 입력된 추가 정보가 필요한 경우 다른 TUIObject 를 인스턴스화하고 ScreenHandler.push_screen_modal() 을 사용하여 표시할 수 있습니다.

텍스트 기반 인터페이스의 제한으로 인해 TUI spokes는 사용자가 확인하거나 검사하거나 채워야 하는 체크박스 또는 항목 목록으로 구성된 매우 유사한 구조를 갖는 경향이 있습니다.

맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat