简体   繁体   English

如何隐藏Tkinter Python中的图片

[英]How can I hide the image in Tkinter Python

I want to hide the image in Tkinter Python module.我想隐藏 Tkinter Python 模块中的图像。 How can I do it?我该怎么做?

For example:例如:

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()

I try the [image].destory() , but it's not working.我尝试[image].destory() ,但它不起作用。

To hide the image in Tkinter, you can use the itemconfig method to change the state of the image to HIDDEN.要隐藏Tkinter中的图片,可以使用itemconfig方法将图片的state改为HIDDEN。 You can then use a button with a command callback to toggle the visibility of the image.然后,您可以使用带有命令回调的按钮来切换图像的可见性。

Here is an example of how you can modify your code to hide the image:以下是如何修改代码以隐藏图像的示例:

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()

The destroy() method is used to destroy a widget and remove it from the parent widget. destroy() 方法用于销毁一个小部件并将其从父小部件中删除。 However, it will not hide the widget - it will completely remove it from the window and free up the resources used by the widget.但是,它不会隐藏小部件 - 它会将它从 window 中完全删除并释放小部件使用的资源。

If you want to remove a canvas object from a canvas, you can use the delete method of the canvas. It takes as a parameter the id of the object to be deleted:如果要从canvas中删除一个canvas object,可以使用canvas的delete方法,参数为要删除的object的id:

canvas.delete(img)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM