简体   繁体   English

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

[英]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. 当我在IDE中运行代码时,按钮绑定事件将自动运行,而不是等待我单击按钮。 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: 问题是您实际上是在bind语句中调用该方法:

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. 代码的另一个问题是printIt方法需要接受两个参数:self和一个事件。 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()

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

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