如何將事件繫結到 Tkinter Canvas 項?


Tkinter 事件可與小元件繫結,以便對小元件執行一組操作。更具體地說,我們還可以透過使用bind(<Button>, callback) 方法將事件處理程式繫結到畫布項。將事件與畫布項繫結使畫布項成為動態的,可以由事件處理程式自定義。

示例

#Import the required Libraries
from tkinter import *
import random

#Create an instance of Tkinter frame
win = Tk()

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

#Crate a canvas
canvas=Canvas(win,width=700,height=350,bg='white')
def draw_shapes(e):
   canvas.delete(ALL)

canvas.create_oval(random.randint(5,300),random.randint(1,300),25,25,fill='O rangeRed2')
canvas.pack()

#Bind the spacebar Key to a function
win.bind("<space>", draw_shapes)
win.mainloop()

輸出

執行上述程式碼將顯示一個包含畫布的視窗。

當我們按下 <Space> 鍵時,它將在畫布視窗中生成隨機形狀。

更新時間:25-5-2021

2K+ 瀏覽

開啟 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.