Python递归函数运行报RecursionError如何避免超出最大递归深度?
递归深度超限错误解决方案
你遇到的报错:
RecursionError: maximum recursion depth exceeded in instancecheck
错误原因
你的代码本质是无上限递归调用,每次直接调用main()都会在调用栈中新增一层,哪怕手动调高递归深度上限,只要持续运行总会触达阈值触发报错。你调整后的代码仅在满足n%2400==0时用root.after调度,其余场景还是直接递归,调用栈仍会持续累积。
修复方案
完全抛弃直接递归逻辑,所有下一次执行都通过tk事件循环的root.after调度,彻底避免调用栈累积:
完整可运行代码
import tkinter as tkin import math import hmac import hashlib n = 0 root = tkin.Tk() canvas1 = tkin.Canvas(root, width=300, height=300) canvas1.pack() label1 = tkin.Label(root, text='Number', fg='green', font=('helvetica', 12, 'bold')) canvas1.create_window(150, 200, window=label1) def dice(serverSeed, clientSeed, nonce): round = 0 nonceSeed = f"{clientSeed}:{nonce}:{round}" hex_str = hmac.new( bytes(serverSeed, 'utf-8'), bytes(nonceSeed, 'utf-8'), hashlib.sha256 ).hexdigest()[0:8] end = 0 for i in range(4): end += int(hex_str[i*2:i*2+2], 16) / math.pow(256, i+1) end = math.floor(end * 10001) / 100 return str(end) def main(): global n n += 1 roll = float(dice( '535e8f53eee1402b242c7eff4038787d3de850c3ba27bde6a370225e1a2f23dd', '8cf82c02b3', n )) if n % 2400 == 0: label1.configure(text=roll) # 所有后续调用都交给事件循环调度,无栈累积 root.after(0, main) button1 = tkin.Button(text='Click Me', command=main, bg='brown', fg='white') canvas1.create_window(150, 150, window=button1) root.mainloop()
优化说明
- 移除了所有直接递归调用,每次
main执行完后通过root.after将下一次执行提交给tk事件循环,每次执行都是独立的调用栈,不会出现深度累积,从根本上解决递归超限问题。 - 去掉了冗余的
sys.setrecursionlimit配置和label1.update()手动刷新调用,由tk主循环自动处理UI更新。 - 如果需要控制执行频率,修改
root.after第一个参数即可,单位为毫秒,比如设置为10就是每10毫秒执行一次。
内容的提问来源于stack exchange,提问作者Krisztian Nagy Zsolt
相关产品推荐
相关产品推荐

