I want to hide the image in Tkinter Python module. 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.
CodePudding user response:
To hide the image in Tkinter, you can use the itemconfig method to change the state of the image to 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. However, it will not hide the widget - it will completely remove it from the window and free up the resources used by the widget.
CodePudding user response:
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.delete(img)