无法清除输出文本:tkinter.TclError:错误文本索引“0”

M.P*_*ree 5 python user-interface textbox tkinter

当运行以下代码并单击 tkinter 按钮时;它产生以下错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "D:\Scypy\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "D:\modpu\Documents\Python\DelMe.py", line 5, in click
    OutputBox.delete(0, END)
  File "D:\Scypy\lib\tkinter\__init__.py", line 3133, in delete
    self.tk.call(self._w, 'delete', index1, index2)
_tkinter.TclError: bad text index "0"
Run Code Online (Sandbox Code Playgroud)

由于某种原因,代码成功清除了输入框中的文本,但未能清除输出框中的文本(而是崩溃了)。

对此的任何帮助将不胜感激,谢谢。

from tkinter import *

def click():
    MainTextBox.delete(0, END)  #This works
    OutputBox.delete(0, END) #This doesn't work

GUI = Tk()
MainTextBox = Entry(GUI, width = 20, bg = "white")
MainTextBox.grid(row = 0, column = 0, sticky = W)
Button(GUI, text = "SUBMIT", width = 6, command = click).grid(row = 1, column = 0, sticky = W)
OutputBox = Text(GUI, width = 100, height = 10, wrap = WORD, background = "orange")
OutputBox.grid(row = 4, column = 0, sticky = W)
OutputBox.insert(END, "Example text")

GUI.mainloop()
Run Code Online (Sandbox Code Playgroud)

小智 7

在这种情况下,这是解决方案:

from tkinter import *

def click():
    MainTextBox.delete(0, END)  
    OutputBox.delete('1.0', END) 

GUI = Tk()
MainTextBox = Entry(GUI, width = 20, bg = "white")
MainTextBox.grid(row = 0, column = 0, sticky = W)
Button(GUI, text = "SUBMIT", width = 6, command = click).grid(row = 1, column = 0, sticky = W)
OutputBox = Text(GUI, width = 100, height = 10, wrap = WORD, background = "orange")
OutputBox.grid(row = 4, column = 0, sticky = W)
OutputBox.insert(END, "Example text")

GUI.mainloop()
Run Code Online (Sandbox Code Playgroud)

  • 如果你能解释一下区别是什么,你的答案会更好。否则,读者必须逐行和逐字符地将您的代码与原始代码进行比较。 (14认同)
  • 你解决了我的问题,但它太奇怪了!为什么索引会是一个内部有浮点数的字符串? (2认同)
  • 代码中唯一的**差异**是在**click()函数的最后一行**。`OutputBox.delete(0, END)` 中的 **参数** 更改为 => `('1.0', END)` 因为文本小部件必须具有索引 **1.0** 而不是 0。 (2认同)