如何在Python Tkinter中隐藏Canvas上的图像?
在Tkinter中隐藏Canvas上的图像
你不能直接对PhotoImage对象调用destroy()来隐藏图像,因为Canvas上的图像是通过create_image()创建的画布元素,需要用Canvas的内置方法来操作这个元素(也就是你用img变量保存的元素ID)。下面是两种可行的方法:
方法1:设置元素状态为隐藏
使用canvas.itemconfigure()方法,将图像元素的state参数设为'hidden',后续需要显示时再设为'normal'即可:
def hide(): canvas.itemconfigure(img, state='hidden')
方法2:清空图像引用
通过canvas.itemconfig()将图像元素的image参数设为空字符串,画布上就会停止显示该图像:
def hide(): canvas.itemconfig(img, image='')
完整修改后的代码
from tkinter import * root = Tk() root.title("Example") root.geometry("500x500") root.resizable(0, 0) def hide(): # 两种方法二选一即可 canvas.itemconfigure(img, state='hidden') # 或者 canvas.itemconfig(img, image='') canvas = Canvas(root, width=500, height=500) canvas.pack() image = PhotoImage(file='example.png') img = canvas.create_image(0, 0, anchor=NW, image=image) # 重命名按钮变量,避免和hide函数重名 hide_btn = Button(root, text="Hide", command=hide) hide_btn_window = canvas.create_window(0, 30, anchor=NW, window=hide_btn) root.mainloop()
内容的提问来源于stack exchange,提问作者Vagif
相关产品推荐
相关产品推荐

