How to undo in tkinter canvas?

I have made an undo function in my program, which is the delete function. I make squares with the MakeRect function, then delete a couple, then make another one and then delete it again. The second deletion attempt did not delete the squares already added in second time. It seems that the variables in the square name tags did not get reduced, leading it to pile up.

Sorry that I have to do it double. Sometimes bugs happen and I didn’t reply you. If you don’t know, here’s the code:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
frame = tk.Frame(root)
frame.pack()

Bottom = tk.Frame(root)
Bottom.pack(side = tk.BOTTOM)
LeftGrid = tk.Frame(Bottom)
LeftGrid.pack(side = tk.LEFT)

CanvasArea = ttk.Frame(Bottom)
CanvasArea.pack(side = tk.LEFT)

CW = 400
CH = 300
LXM = (CW / 2)
LYM = (CH / 2)
TLX = tk.IntVar()

LLX = tk.Label(LeftGrid, text = 'X:')
LLX.grid(row = 2, column = 1)
TLXInput = ttk.Entry(LeftGrid, textvariable = TLX)
TLXInput.grid(row = 2, column = 2)

MainCanvas = tk.Canvas(CanvasArea, bg = 'white', height = CH, width = CW)
MainCanvas.pack(side = tk.LEFT)

N = 0

ObjectList = [0]

def Rectangle(Name, Canvas, LX, LY, SX, SY, MC, LO, LT):
    Canvas.create_rectangle((LX + SX), (LY + SY), (LX - SX), (LY - SY), fill = MC, outline = LO, width = LT, tags = Name)

def MakeRect():
    global ObjectList
    global N
    print (ObjectList)
    print (N)
    N = N + 1
    print (N)
    Rectangle(N, MainCanvas, LXM + TLX.get(), LYM , 1, 1, 'red', 'black', 1)
    ObjectList.insert(N, N)
    print (ObjectList)
    print (N)

def DeleteObj():
    global ObjectList
    global N
    print (ObjectList)
    print (N)
    MainCanvas.delete(N)
    del ObjectList[-1]
    N = N - 1

    print (ObjectList)
    print (N)

DO = tk.Button(LeftGrid, text = 'Delete',command = DeleteObj)
DO.grid(row = 0, column = 1)

GridButton(LeftGrid, 'a', 'Make Rectangle', None, MakeRect ,1, 0)

root.mainloop()

It might help to mention OS and Python and tk versions. How do you ‘run’ the code twice. Presumably, there is some difference between first and second.

Here is how I meant: I make squares with the MakeRect function, then delete a couple, then make another one and then delete it again. The second deletion attempt is my “second run” and did not delete the squares already added in second time. I am going to clarify this in this post.

Sorry that I have to do it double. Sometimes bugs happen and I didn’t reply you for 1st time.

Re create_rectangle, a tag is not a name or id. The method will return an id (a string) for the rectangle, so store that in the stack (list) of objects, and use that id when you want to delete the object from the canvas.

1 Like