[파이썬] wxPython `wx.App`: 이벤트 루프

In wxPython, the wx.App class is the main entry point for creating an application. It represents the application itself and acts as a container for many other controls and windows. One of the key features of wx.App is its ability to handle events through the event loop.

The Event Loop

The “이벤트 루프” (event loop) is a fundamental concept in graphical user interface programming. It allows the application to respond to user actions and system events by dispatching the appropriate event handlers.

Here is an example of how to create a basic wxPython application with an event loop:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super().__init__(parent, title=title, size=(400, 300))
        self.Bind(wx.EVT_CLOSE, self.on_close)
        self.Show()

    def on_close(self, event):
        self.Destroy()

app = wx.App()
frame = MyFrame(None, "My First wxPython App")
app.MainLoop()

In this example, we start by importing the wx module. We then define a custom class MyFrame that inherits from wx.Frame. This class represents the main frame of our application.

Within the MyFrame class, we override the __init__ method to create the main window and bind the EVT_CLOSE event to the on_close method. This event is triggered when the user tries to close the window. In our on_close method, we call Destroy() to properly clean up and close the application.

Next, we create an instance of wx.App to represent our application. We then create an instance of MyFrame and pass None as the parent window, and provide a title for our main frame.

Finally, we call app.MainLoop() to start the event loop. This method runs continuously and dispatches events to their respective event handlers.

Conclusion

The wx.App class and the event loop are essential components of wxPython applications. Understanding how to create an instance of wx.App and utilize the event loop allows you to build responsive and interactive graphical user interfaces in Python.