python3中目前有个启动线程的函数def btn_tili_click global thread1 thread1 = threadingThreadtarget=btn_tili_click_T thread1setDaemonTrue thread1start我想让其变为通用函数btn_clicktype然后通过这个type去启动对应的函数比如type为hunha
你可以使用一个字典来存储不同类型对应的函数,然后在通用函数中根据传入的类型选择相应的函数进行启动。以下是示例代码:
import threading
def hunhai():
print("hunhai function")
def tili():
print("tili function")
def btn_click(type):
func_dict = {
"hunhai": hunhai,
"tili": tili
}
if type in func_dict:
thread = threading.Thread(target=func_dict[type])
thread.setDaemon(True)
thread.start()
else:
print("Invalid type")
# 示例调用
btn_click("hunhai")
btn_click("tili")
btn_click("invalid")
输出结果:
hunhai function
tili function
Invalid type
在示例代码中,btn_click函数接收一个type参数,然后根据传入的type选择对应的函数进行启动。如果传入的type在字典func_dict中存在对应的函数,则创建一个新的线程并启动该函数。否则,输出"Invalid type"表示类型无效
原文地址: https://www.cveoy.top/t/topic/iHGY 著作权归作者所有。请勿转载和采集!