在下面的实验中,当我按下Button1时,标签框应该出现,而确实如此。但是如果按下按钮2后按下它,我会在消失函数的delete命令中引用一个问题,然后在tk模块中引用“标记搜索表达式中的无效布尔运算符”。
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()
你能帮忙吗?我找不到错误消息非常helfpul。我已经能够使用.delete方法在我在文档中找到的简单示例中工作,但不是在这里。
答案 0 :(得分:1)
代码应该记住create_window()
调用的返回值。然后将其传递给Canvas.delete
方法:
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)