如何在 Tkinter 中將單擊事件繫結到畫布?
Canvas 元件無疑是 tkinter 中最強大的元件。它可以用來建立和開發從自定義元件到完整使用者介面的所有內容。我們甚至可以繫結單擊事件來處理畫布及其物件。
示例
在本示例中,我們將在畫布元件內新增一張影像,並將一個按鈕物件繫結到畫布上以刪除影像。
為了繫結一個單擊事件,我們可以使用tag_bind()方法,並使用delete(image object)刪除影像。
#Import the required library from tkinter import* #Create an instance of tkinter frame win= Tk() #Set the geometry win.geometry("750x280") #Create an canvas object canvas= Canvas(win, width= 1000, height= 750) #Load an image inside the canvas smiley = PhotoImage(file='smile.gif') #Create an image in the canvas object image_item = canvas.create_image((200, 140), image=smiley) #Bind the Button Event to the Canvas Widget canvas.tag_bind(image_item, '<Button-1>', lambda e: canvas.delete(image_item)) canvas.pack() win.mainloop()
結果
執行上述程式碼將顯示一張笑臉影像。
現在,在影像上“左鍵單擊”滑鼠按鈕,它將立即從畫布中刪除。
廣告