-1

I am just trying to make a notepad using python Tkinter. when I tried to code for the undo and redo command I got error.


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()

ERROR

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

Rajan Sharma
  • 2,211
  • 3
  • 21
  • 33

1 Answers1

0

Here you're calling edit_undo:

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

Of course, as the window is just being created, there's nothing to undo yet. You should pass the function instead of the result of calling it:

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

The same happens on the next line.

ForceBru
  • 43,482
  • 10
  • 63
  • 98