禁用按钮仍可捕捉长任务期间的单击。在长任务期间,按钮是灰色的,但是如果在长任务期间单击它,则在长任务完成后单击事件触发。例如:
def onClick(self, evt):
self.btn.Disable()
for i in range (1000):
print i
self.btn.Enable()按钮在执行long for循环之前禁用自身,但是如果我们在for循环期间单击按钮,它将再次启动for循环,因为它在for循环结束后再次调用onClick函数。
知道如何禁用单击事件吗?
发布于 2018-10-24 15:59:04
虽然我怀疑您是否应该以这种方式编写您的长时间运行事件,但是您可以通过在按钮单击上使用Unbind、执行长时间运行任务、使用Yield来使用任何后续的按钮单击,然后在任务Bind的末尾再次对该按钮进行编码来实现您想要的结果。即
import wx
import time
class ButtonFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None)
self.btn = wx.Button(self, -1, "Click Me")
self.btn.Bind(wx.EVT_BUTTON, self.onClick)
self.Centre()
self.Show()
def onClick(self, event):
self.btn.Unbind(wx.EVT_BUTTON)
for i in range (10):
time.sleep(1)
print( i )
wx.GetApp().Yield() # Yielding allows button events to be used up
self.btn.Bind(wx.EVT_BUTTON, self.onClick)
print ("Accepting clicks again")
if __name__ == "__main__":
app = wx.App()
ButtonFrame()
app.MainLoop()发布于 2018-10-24 05:29:11
老实说,我并没有真正明白你的要求。
您的代码工作如下:
如果要禁用按钮,则应在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
发布于 2018-11-14 15:30:10
事实上,这比我的第一个答案要容易得多。没有理由使用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()https://stackoverflow.com/questions/52960024
复制相似问题