简体   繁体   中英

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()

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM