如何在 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 千余次浏览

开启你的 职业 生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.