如何在 Tkinter 中將空格鍵繫結到某種方法?


可以透過與鍵或滑鼠繫結 Tkinter 方法,從而在應用程式中執行某些操作或事件。假設對於特定應用程式我們希望繫結 <空格> 鍵來執行某些操作。我們可以透過定義 bind(<key>, callback) 方法將任何鍵繫結到特定操作或事件。

示例

在這個示例中,我們將使用 Python 中的隨機模組建立隨機寬度和高度的矩形。因此,每當我們按下該鍵時,它都會在螢幕上生成一些隨機形狀。

#Import the required Libraries
from tkinter import *
import random

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

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

canvas.create_rectangle(random.randint(5,300), random.randint(1,300), 25, 25, fill='khaki3')
canvas.pack()

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

輸出

執行上述程式碼,它會顯示一個視窗,使用者在按下鍵盤上的 <空格> 鍵時,它會生成隨機形狀。

更新於: 04-May-2021

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告