繁体   English   中英

单击之前运行的wxpython按钮事件

[英]wxpython button event running before click

当我在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()

问题是您实际上是在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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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