[英]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.