如何在 Tkinter 上隱藏和顯示 Canvas 項?


Canvas 小部件是 Tkinter 中多種用途的小部件之一。它用於許多應用程式中,用於設計圖形使用者介面,如設計、新增圖片、建立圖形等。我們可以在 Canvas 小部件本身中新增小部件。Canvas 控制元件內部的小部件有時稱為“Canvas 項”。

如果我們想透過一個按鈕顯示或隱藏畫布專案,那麼可以使用“state”屬性在 itemconfig(id, state)方法中實現。

示例

在這個示例中,我們將在 Canvas 中新增一張圖片,並使用一個按鈕在 Canvas 中顯示/隱藏圖片。

# Import the required libraries
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Globally Declare the Boolean value
show = True

def on_click():
   global show

   # Determine if the image is hidden or not
   if show:
      canvas.itemconfig(1, state='hidden')
      show = False
   else:
      canvas.itemconfig(1, state='normal')
      show = True

# Add a Canvas widget
canvas = Canvas(win, width=440, height=300)
canvas.pack()

# Add image to the canvas
img = ImageTk.PhotoImage(file="bird.jpg")
canvas.create_image(200, 200, image=img, anchor=CENTER)

# Add a Button to Show/Hide Canvas Items
ttk.Button(win, text="Show/Hide", command=on_click).pack()

win.mainloop()

輸出

如果我們執行上述程式碼,它將顯示一個包含圖片和按鈕的視窗,單擊該按鈕來觸發隱藏和顯示圖片的功能。

現在,單擊該按鈕來顯示/隱藏圖片。

更新時間: 2021 年 6 月 19 日

3 千餘次瀏覽

開啟你的 職業 生涯

透過完成課程獲得認證

開始
廣告