python使一个函数在新线程中运行的装饰器

python在用tk编程时, 界面响应函数最好在另外一个线程中运行, 以免界面没有响应.
为方便使用, 封装了一个装饰器, 调用函数时自动在另外一个线程中运行.
示例代码如下:

import threading

def run_in_thread(func):
    def wrapper(*args, **kwargs):
        thread = threading.Thread(target=func, args=args, kwargs=kwargs)
        thread.start()
    return wrapper

@run_in_thread
def my_function(a):
    # 在新线程中运行的函数
    print(f"运行在新线程中:{a}")

# 调用函数,将在新线程中运行
my_function(10)
posted @ 2023-07-18 17:41  顺其自然,道法自然  阅读(16)  评论(0编辑  收藏  举报