如何修复'_tkinter.TclError:没什么可撤消的'错误

时间:2019-07-31 08:44:00

标签: python python-3.x tkinter undo-redo tkinter-text

我只是想用python Tkinter做一个记事本。当我尝试为undo和redo命令编写代码时,出现错误。


from tkinter import *
from tkinter import filedialog
from tkinter import messagebox


class TextEditor:
    current_file = "no_file"
    def __init__(self, master):
        self.master = master
        master.title("text pad")
        self.text_area = Text(self.master, undo=True, autoseparators=True, maxundo=-1)
        self.text_area.pack(fill=BOTH, expand=1)
        self.main_menu = Menu()
        self.master.config(menu=self.main_menu)
        self.edit_menu = Menu(self.main_menu, tearoff=FALSE)
        self.main_menu.add_cascade(label="Edit", menu=self.edit_menu)

        self.edit_menu.add_command(label="Undo", command=self.text_area.edit_undo())
        self.edit_menu.add_command(label="Redo", command=self.text_area.edit_redo())
        self.edit_menu.add_separator()

root = Tk()

te = TextEditor(root)

root.mainloop()

错误

Traceback (most recent call last):
  File "C:/Users/divya/PycharmProjects/untitled/text_editor.py", line 140, in <module>
    te = TextEditor(root)
  File "C:/Users/divya/PycharmProjects/untitled/text_editor.py", line 102, in __init__
    self.edit_menu.add_command(label="Undo", command=self.text_area.edit_undo())
  File "C:\Users\divya\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3242, in edit_undo
    return self.edit("undo")
  File "C:\Users\divya\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3198, in edit
    return self.tk.call(self._w, 'edit', *args)
_tkinter.TclError: nothing to undo

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

您在这里打来电话 edit_undo

self.edit_menu.add_command(label="Undo", command=self.text_area.edit_undo())

当然,由于刚刚创建了窗口,因此没有任何要撤消的操作。您应该传递 function 而不是调用它的结果:

self.edit_menu.add_command(label="Undo", command=self.text_area.edit_undo) # no parentheses

下一行也是如此。