Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีซ่อนและแสดงรายการบน Canvas ใน Tkinter


Widget Canvas เป็นหนึ่งใน widget ที่หลากหลายใน Tkinter ใช้ในหลายแอปพลิเคชันสำหรับออกแบบ GUI เช่น การวาดภาพ เพิ่มภาพ สร้างกราฟิก เป็นต้น เราสามารถเพิ่ม widget ลงใน Canvas เองได้ Widget ที่อยู่ภายใน canvas เรียกว่า "Canvas Items"

หากต้องการแสดงหรือซ่อน canvas items ผ่านปุ่ม สามารถทำได้โดยใช้คุณสมบัติ state ในเมธอด itemconfig(id, state)

ตัวอย่าง

ในตัวอย่างนี้ จะเพิ่มภาพใน 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()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่างพร้อมภาพและปุ่มเพื่อทริกเกอร์ฟังก์ชันซ่อน/แสดงภาพ

วิธีซ่อนและแสดงรายการบน Canvas ใน Tkinter

คลิกปุ่มเพื่อแสดง/ซ่อนภาพ