单击之前运行wxpython按钮事件

时间:2014-07-01 18:30:30

标签: python user-interface wxpython

当我在IDE中运行代码时,按钮绑定事件会自动运行,而不是等待我单击按钮。然后,当事件完成并且面板出现时,按钮在单击时不执行任何操作。

我想我已经按照我在网上找到的例子,但它仍然有这种奇怪的行为?有任何想法吗?谢谢!

代码如下。 (更新了额外的位)

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 个答案:

答案 0 :(得分:0)

问题是你实际上是在bind语句中调用该方法:

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

删除括号以停止此行为,如下所示:

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

现在它应该按预期工作。

代码的另一个问题是 printIt 方法需要接受两个参数:self和一个事件。您的代码已编辑为正常运行:

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