wxpython在长时间任务中禁用按钮仍然吸引点击

时间:2018-10-24 01:46:03

标签: python wxpython

在长任务中,禁用按钮仍会捕获点击。在长任务中,该按钮显示为灰色,但如果在长任务中单击该按钮,则在长任务完成后会触发click事件。例如

def onClick(self, evt):
    self.btn.Disable()
    for i in range (1000):
        print i
    self.btn.Enable()

按钮在执行长的 for 循环之前会先禁用自身,但是如果我们在for循环中单击该按钮,它将再次启动for循环,因为它会调用 onClick 函数在for循环结束后再次显示。

有什么想法也要禁用点击事件吗?

3 个答案:

答案 0 :(得分:0)

说实话,我并没有真正理解您的要求。

您的代码如下:

  1. 单击该按钮时,该按钮(即self.btn)被禁用
  2. 它将保持禁用状态并执行for循环
  3. 执行完for循环后,按钮将恢复活动状态

如果要禁用该按钮,则应在onclick事件之外进行操作。 例如:

self.btn.Disable()  # This will grey out the button, you can't click it, so the following onClick function wouldn't be triggered
def onClick(self, evt):
    # do something

如果您想使用该按钮触发任务执行,并在任务处于执行中间时禁用触发该任务的按钮,则最好的方法是使用多线程。您可以查看以下两个链接以获取更多信息:

http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/ https://wiki.wxpython.org/LongRunningTasks

答案 1 :(得分:0)

尽管我不确定您是否应该以这种方式编写长时间运行的事件,但是您可以通过在按钮单击上使用Unbind来实现所需的功能,使用{{1 }}用完所有随后的按钮单击,然后在任务Yield结束时再次使用该按钮。 即

Bind

答案 2 :(得分:0)

实际上,这比我的第一个答案要容易。没有理由UnBind,只需在重新启用按钮之前使用Yield就可以了:

import wx
import time

class ButtonFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,None,-1,"Disable Button Events")
        panel = wx.Panel(self, -1)
        self.btn = wx.Button(panel, -1, "Click Me", pos=(10,10), size=(80,30))
        self.btn.Bind(wx.EVT_BUTTON, self.onClick)
        self.Show()

    def onClick(self, event):
        self.btn.Disable()
        for i in range (10):
            time.sleep(1)
            print("Long task running",i)
        wx.GetApp().Yield() # Yielding allows button events to be used up
        self.btn.Enable()
        print("Accepting clicks again")

if __name__ == "__main__":

    app = wx.App()
    ButtonFrame()
    app.MainLoop()