[英]How can I hide the image in Tkinter Python
我想隐藏 Tkinter Python 模块中的图像。 我该怎么做?
例如:
from tkinter import *
root = Tk()
root.title("Example")
root.geometry("500x500")
root.resizable(0, 0)
def hide():
# How can I hide the 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 = Button(root, text="Hide", command=hide)
hide = canvas.create_window(0, 30, anchor=NW, window=hide)
root.mainloop()
我尝试[image].destory()
,但它不起作用。
要隐藏Tkinter中的图片,可以使用itemconfig方法将图片的state改为HIDDEN。 然后,您可以使用带有命令回调的按钮来切换图像的可见性。
以下是如何修改代码以隐藏图像的示例:
from tkinter import *
root = Tk()
root.title("Example")
root.geometry("500x500")
root.resizable(0, 0)
# Initialize a boolean variable to keep track of the image visibility
image_visible = True
def hide():
global image_visible
# Toggle the image visibility
image_visible = not image_visible
# Use itemconfig to change the state of the image
canvas.itemconfig(img, state=NORMAL if image_visible else HIDDEN)
canvas = Canvas(root, width=500, height=500)
canvas.pack()
image = PhotoImage(file='physics_image.jpg')
img = canvas.create_image(0, 0, anchor=NW, image=image)
hide = Button(root, text="Hide", command=hide)
hide = canvas.create_window(0, 30, anchor=NW, window=hide)
root.mainloop()
destroy() 方法用于销毁一个小部件并将其从父小部件中删除。 但是,它不会隐藏小部件 - 它会将它从 window 中完全删除并释放小部件使用的资源。
如果要从canvas中删除一个canvas object,可以使用canvas的delete
方法,参数为要删除的object的id:
canvas.delete(img)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.