对after的调用导致运行时错误:超出了最大递归深度

2024-04-20 09:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是tkinter,我试图将字符串[在本例中是原始文件]与文本小部件中的文本进行比较。这是函数,我在这里调用函数:

def checkText():
    if(text.get("1.0", "end-1c") != currentText):
        print("Changed")

    root.after(1000, checkText())

我打电话给:

^{pr2}$

它返回错误:

^{3}$

除了几百个“文件”主.py“,第65行,在checkText中”

可能是我忽视了一些显而易见的事情,但我很感激你的帮助。在

这些是程序中使用或引用函数的唯一位置,但仅在这种情况下,currentText的定义如下:

myfile = tkFileDialog.askopenfile(title='Open a file', mode='r')
    text.delete('1.0', END)
    loadedfile = myfile.read()
    currentText = myfile.read()

loadedFile直接放在文本小部件中,工作正常,所以我假设currentText应该与小部件中的loadedFile/text相同。在

谢谢。在

编辑:格式化,我也意识到我可以说currentText = loadedFile来简化它,但是我在问题中保留了原始代码

编辑:获取文本的整个函数

def fileOpen(textView):
try:
    myfile = tkFileDialog.askopenfile(title='Open a file', mode='r')
    text.delete('1.0', END)
    loadedfile = myfile.read()
    currentText = loadedFile
    currentFile = myfile.name
    currentName = currentFile
    currentName = currentName.rsplit('/', 1)[-1] #get the 'name.ext' part only
    currentName = currentName.rsplit('\\', 1)[-1] #incase you're using windows
    currentFileButton.config(text = currentName)
    myfile.close()
    textView.insert("end", loadedfile)
except:
    return

def saveAs(): #define how to save files
try:
    global text
    t = text.get("1.0", "end-1c")
    saveLocation = tkFileDialog.asksaveasfilename()
    file1 = open(saveLocation, "w+")
    file1.write(t)
    file1.close()
except:
    return

稍后:

text = Text(textFrame, bd=0, bg=color, fg=textColor) #make text editor box

Tags: 函数text文本readget部件defmyfile
1条回答
网友
1楼 · 发布于 2024-04-20 09:07:40

我终于明白了。正如你所说,这很明显,但实际上不是那么明显。在

问题在于您对after的调用。在

当调用after时,需要传递一个时间和一个回调,这是在给定时间之后将被调用的函数。注意,必须传递的是一个函数。在

但是当您调用root.after(1000, checkText())时,第二个参数是而不是一个函数。它是一个,对应于checkText函数的返回值。在


checkText()传递给after时会发生什么情况:

  1. checkText调用时没有参数
  2. 返回值被传递给after

但是当您调用checkText时,到达了对root.after(1000, checkText())的新调用,并且必须对checkText()求值,因此调用checkText。在

每个调用都是立即的(即,它不会在1000毫秒之后发生),因为需要对checkText()表达式进行求值才能传递给after。在


正如我所说,after方法的第二个参数是一个函数。因此,{cd17>是正确的。在

完整代码:

def checkText():
    if(text.get("1.0", "end-1c") != currentText):
        print("Changed")

    root.after(1000, checkText)

root.after(1000, checkText)

这将有效地安排checkText函数在1000毫秒后被调用。在

相关问题 更多 >