You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:48:41