【发布时间】:2021-08-10 00:48:23
【问题描述】:
我想知道如何编写一个重复而不收到错误消息的函数:
RecursionError:instancecheck 中超出最大递归深度_
重复的递归函数是main():
import tkinter as tkin
import math
import hmac
import hashlib
import sys
n = 0
sys.setrecursionlimit(2450)
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 = '{}:{}:{}'.format(clientSeed, nonce, round)
hex = hmac.new(bytes(serverSeed, 'utf-8'), bytes(nonceSeed, 'utf-8'), hashlib.sha256).hexdigest()[0:8]
i = 0
end = 0
while i < 4:
end += int(hex[i*2:i*2+2], 16) / math.pow(256, i+1)
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)
label1.update();
main()
button1 = tkin.Button(text='Click Me',command=main, bg='brown',fg='white')
canvas1.create_window(150, 150, window=button1)
root.mainloop()
编辑:
增加了递归限制和root.after(int, function)
limit = 2400
def main ():
global n
global max
n += 1
roll = float(dice('535e8f53eee1402b242c7eff4038787d3de850c3ba27bde6a370225e1a2f23dd', '8cf82c02b3', n))
if n % limit == 0:
label1.configure(text=roll)
label1.update();
limit+=2400
root.after(0, main)
else:
main()
【问题讨论】:
-
为什么要无限递归循环?请改用 while 循环。
-
您正在创建一个没有退出条件的递归循环。将 main 函数中的
main()移动到else块中。 -
在“点击我”之后 main() 永远不会返回
-
不要使用递归代替循环。这不是 Scheme。
标签: python python-3.x function loops recursion