Search code examples
pythonwxpython

How could I successfully run onButton during startup?


import wx

class MyForm(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Test")
        panel = wx.Panel(self, wx.ID_ANY)
        #Button is created; binded to onButton
        button = wx.Button(panel, id=wx.ID_ANY, label="Press Me")
        button.Bind(wx.EVT_BUTTON, self.onButton)

    def onButton(self,EVT_BUTTON):
        print("Hello world!")

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    #Runs Button command on startup
    MyForm.onButton()

I want onButton() to run at startup, and have it be able to run when the wx.Button is pressed. Unfortunetly, it comes up with this error: >TypeError: onButton() missing 2 required positional arguments: 'self' and 'EVT_BUTTON'


Solution

  • It is slightly more difficult. I am guessing you are a beginner to programming. If so, I suggest, you learn some more basics. Doing GUI applications is a bit more advanced topic.

    So, firstly, for your wxPython program to run, you must start an event loop, so your program should have something like this:

    if __name__ == "__main__":
        app = wx.App(False)
        frame = MyForm()
        frame.Show()
        app.MainLoop()
    

    You defined your function onButton with 2 parameters. Therefore you must supply them when calling the function. The first one is instead of the self, and that is the frame. The second is named EVT_BUTTON (and giving the variable this name suggests that you actually do not understand these concepts, and that's the reason why I suggested that you start with studying basics).

    So you could call

    frame.OnButton(None)
    

    before calling app.MainLoop() and the code will run. But that's probably not enough.