【问题标题】:wxpython button event running before click在单击之前运行的 wxpython 按钮事件
【发布时间】:2014-07-01 18:30:29
【问题描述】:

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

【问题讨论】:

  • 您发布的代码不会运行。请发布一个最小的工作示例

标签: python user-interface wxpython


【解决方案1】:

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

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

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

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

现在它应该可以正常工作了。

代码的另一个问题是 printIt 方法需要接受两个参数:self 和 event。这是您的代码编辑后可以正常工作:

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

【讨论】:

  • 我只是注意到括号问题并在事件问题上绊倒了,所以你把它们都清除了,谢谢!!最后一个问题,这里不是 python 专业人士,如果我想在单击按钮时将参数传递给我想运行的函数怎么办?我可以不加括号吗???
  • 您必须使用 lambda 或 functools 来传递参数。 wxPython wiki 上有一些很好的例子:wiki.wxpython.org/Passing%20Arguments%20to%20Callbacks
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 1970-01-01
相关资源
最近更新 更多