Jay B
Jay B

Reputation: 125

wxpython button event running before click

When I run the code in my IDE, the button bind event runs automatically instead of waiting for me to click the button. Then when the event is complete and the panel appears, the button does nothing when clicked.

I think I've followed the examples I've found on the web, but it still has this strange behavior??? Any ideas? Thanks!

Code is below. (Updated with the extra bits)

def main():
    pass

if __name__ == '__main__':
    main()


import wx

class Frame(wx.Frame):

    def __init__(self,parent,id):
        self.headr(parent,id)



    def headr(self,parent,id):
        wx.Frame.__init__(self,parent,id, 'My Program', size =(300,300))
        panel=wx.Panel(self)
        status = self.CreateStatusBar()


        uploadButton = wx.Button(panel,label="Upload",pos=(20, 30))
        uploadButton.Bind(wx.EVT_BUTTON,self.printIt())


    def printIt(self):
        print("Function has run")

if __name__== '__main__':
    app=wx.App()
    frame = Frame(parent=None,id=1)
    frame.Show()
    app.MainLoop()

Upvotes: 1

Views: 1202

Answers (1)

Mike Driscoll
Mike Driscoll

Reputation: 33071

The problem is that you are actually calling the method in the bind statement:

uploadButton.Bind(wx.EVT_BUTTON,self.printIt())

Remove the parentheses to stop this behavior, like so:

uploadButton.Bind(wx.EVT_BUTTON,self.printIt)

Now it should work as you expect.

Another problem with the code is that the printIt method needs to accept two arguments: self and an event. Here's your code edited to work properly:

import wx

class Frame(wx.Frame):

    def __init__(self,parent,id):
        self.headr(parent,id)



    def headr(self,parent,id):
        wx.Frame.__init__(self,parent,id, 'My Program', size =(300,300))
        panel=wx.Panel(self)
        status = self.CreateStatusBar()


        uploadButton = wx.Button(panel,label="Upload",pos=(20, 30))
        uploadButton.Bind(wx.EVT_BUTTON,self.printIt)


    def printIt(self, event):
        print("Function has run")

if __name__== '__main__':
    app=wx.App()
    frame = Frame(parent=None,id=1)
    frame.Show()
    app.MainLoop()

Upvotes: 1

Related Questions