1

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()
1
  • The code as you posted it will not run. Please post a minimal working example Commented Jul 1, 2014 at 18:41

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I was just noticing the parenthesis issue and tripping on the event issue as well, so you clear both of them up, thanks!! One last question, not a python pro here, what if I wanted to pass an argument to the function I wanted to run when the button is clicked? Can I do that with no parenthesis???
You have to use a lambda or functools to pass an argument along. There are some good examples of both on the wxPython wiki: wiki.wxpython.org/Passing%20Arguments%20to%20Callbacks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.