WX 에서 커서 추가하기

Beginner

This tutorial is from open-source community. Access the source code

소개

이 튜토리얼에서는 WX 에서 데이터 좌표를 보고하는 커서를 추가하는 과정을 안내합니다. 다양한 플롯, 차트 및 그래프를 생성하는 도구를 제공하는 Python 용 플로팅 라이브러리인 Matplotlib 을 사용합니다.

VM 팁

VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접근하십시오.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.

학습 중 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.

캔버스 프레임 생성

먼저, Matplotlib 플롯을 담을 캔버스 프레임을 생성합니다. 커서 기능을 시연하기 위해 사인 곡선 플롯을 추가합니다.

class CanvasFrame(wx.Frame):
    def __init__(self, ):
        super().__init__(None, -1, 'CanvasFrame', size=(550, 350))

        ## Create a Figure and add a subplot
        self.figure = Figure()
        self.axes = self.figure.add_subplot()
        t = np.arange(0.0, 3.0, 0.01)
        s = np.sin(2*np.pi*t)

        ## Plot the sinusoidal curve
        self.axes.plot(t, s)
        self.axes.set_xlabel('t')
        self.axes.set_ylabel('sin(t)')

        ## Create a FigureCanvas to display the plot
        self.figure_canvas = FigureCanvas(self, -1, self.figure)

        ## Bind the motion_notify_event to update the status bar
        self.figure_canvas.mpl_connect(
            'motion_notify_event', self.UpdateStatusBar)

        ## Bind the enter_window event to change the cursor
        self.figure_canvas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor)

        ## Create a sizer and add the FigureCanvas to it
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.figure_canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        ## Create a status bar to report the cursor location
        self.statusBar = wx.StatusBar(self, -1)
        self.SetStatusBar(self.statusBar)

        ## Create a toolbar to navigate the plot
        self.toolbar = NavigationToolbar2Wx(self.figure_canvas)
        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        self.toolbar.Show()

커서 변경

다음으로, 캔버스 프레임에 진입할 때 커서를 변경하는 메서드를 정의합니다. 이 경우, 커서를 bullseye(과녁) 로 변경합니다.

def ChangeCursor(self, event):
    self.figure_canvas.SetCursor(wx.Cursor(wx.CURSOR_BULLSEYE))

상태 표시줄 업데이트

마지막으로, 마우스가 플롯 위로 이동할 때마다 커서 위치로 상태 표시줄을 업데이트하는 메서드를 정의합니다.

def UpdateStatusBar(self, event):
    if event.inaxes:
        self.statusBar.SetStatusText(f"x={event.xdata}  y={event.ydata}")

요약

축하합니다! Matplotlib 을 사용하여 데이터 좌표를 보고하는 커서를 WX 에 성공적으로 추가했습니다. 이 튜토리얼에 설명된 단계를 따르면 필요에 맞게 커서를 쉽게 사용자 정의할 수 있습니다.