Python中实现按键终止循环并调用函数的问题求助
解决函数循环调用仅执行一次的问题
嘿,我一眼就瞅到问题出在哪了!你在loop_display的循环里写的是function,这只是引用了函数对象,根本没真正调用它啊!就好比你指着一个工具说“工具”,但没动手用它,当然不会有效果。而你加的print "next"是直接执行的语句,所以能正常循环跑起来。
修正后的代码
把循环里的function改成function(),这样每次循环才会实际调用传入的函数:
import thread import time def input_thread(a_list): raw_input() a_list.append(True) def loop_display(function): a_list = [] thread.start_new_thread(input_thread, (a_list,)) while not a_list: function() # 这里必须加括号! # print "next" time.sleep(2) # 举个测试用的函数例子 def test_function(): print("函数正在循环执行...") loop_display(test_function)
额外提醒
- 你的原代码没导入
thread和time模块,实际运行时一定要加上,不然会直接报错。 - 如果用的是Python 3,记得把
raw_input()改成input(),这俩版本的输入函数不一样。
内容的提问来源于stack exchange,提问作者FallenSpaces
相关产品推荐
相关产品推荐

