Reputation: 223
In the experiment below, the tagbox Label should appear when I press the Button1, and it does. But if I follow that with a press on Button2, I get an error referencing a problem in the delete command of the disappear function, then referring to an "invalid boolean operator in tag search expression" in a tk module.
from tkinter import *
from tkinter import ttk
class MainWindow(Frame):
def __init__(self,master):
super().__init__()
self.pack(fill=Y, side=LEFT)
self.booking_canvas = Canvas(self, width=400,
height=100,background="red")
self.button1 = Button(self.booking_canvas, text = "Appear", command =
self.appear)
self.button2 = Button(self.booking_canvas, text="Disappear",
command=self.disappear)
self.booking_canvas.create_window(20,10,window = self.button1)
self.booking_canvas.create_window(80, 10, window=self.button2)
self.booking_canvas.pack(side=LEFT)
def appear(self):
self.tagbox = Label(self.booking_canvas,text="Hello")
self.booking_canvas.create_window(200,10,window = self.tagbox, anchor
= NW)
def disappear(self):
self.booking_canvas.delete(self.tagbox)
root = Tk()
MainWindow(root)
root.mainloop()
Can you help? I'm not finding the error message very helfpul. I've been able to make the .delete method work in the simple examples I've found in the documentation, but not here.
Upvotes: 1
Views: 972
Reputation: 369074
The code should remember the return value of the create_window()
call. Then pass it to Canvas.delete
method:
def __init__(self, master):
...
self.item = None
def appear(self):
self.tagbox = Label(self.booking_canvas,text="Hello")
self.disappear() # remove old one
self.item = self.booking_canvas.create_window(200, 10,
window=self.tagbox, anchor=NW)
def disappear(self):
if self.item:
self.booking_canvas.delete(self.item)
Upvotes: 2