由于主循环被锁定,窗口变暗my_function
。
尝试异步调用您的方法。它可以用 gobject 或 gdk 线程来实现。此示例使用 python 线程。
许多打印来描述功能的顺序:
import threading
class Thread(threading.Thread):
def __init__(self,callback,*args,**kwargs):
self.__callback = callback
threading.Thread.__init__(self,*args,**kwargs)
def run(self):
try:
if self.__target:
print('thread')
_self = self.__kwargs.get('self',self.__args[0])
self.__callback(_self, self.__target(*self.__args, **self.__kwargs))
finally:
# Avoid a refcycle if the thread is running a function with
# an argument that has a member that points to the thread.
del self.__target, self.__args, self.__kwargs
def background(callback):
print('background')
def wrapper(fun):
print('wrapper')
def inner(*args,**kwargs):
print('inner')
Thread(callback=callback,target=fun,args=args,kwargs=kwargs).start()
return inner
return wrapper
def spinner(fun):
def inner(self,*args,**kwargs):
self.show()
result = fun(self,*args,**kwargs)
self.hide()
return result
return inner
def spinner_hide(fun):
def inner(self,*args,**kwargs):
result = fun(self,*args,**kwargs)
self.hide()
return result
return inner
def spinner_show(fun):
def inner(self,*args,**kwargs):
self.show()
result = fun(self,*args,**kwargs)
return result
return inner
class A(object):
@spinner_hide
def my_function_callback(self,data):
print('callback')
print(data)
@spinner_show
@background(my_function_callback)
def my_function(self, input):
# do something here that takes long time
print(input)
output=input
return output
def show(self): print('showed')
def hide(self): print('hidden')
a=A()
a.my_function('gogo')
使用 IDLE 运行示例的结果
background
wrapper
showed
inner
thread
>>>
gogo
callback
gogo
hidden
>>>
表示主线程变为IDLE,进入后台后输出。