-1

我只是想用 python Tkinter 做一个记事本。当我尝试为撤消和重做命令编写代码时,我得到了错误。


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

4

1 回答 1

0

你在这里打电话 edit_undo

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

当然,由于窗口刚刚被创建,还没有什么可以撤消的。您应该传递函数而不是调用它的结果:

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

下一行也会发生同样的情况。

于 2019-07-31T08:51:09.547 回答