如何在 Tkinter 中繫結所有數字鍵?
在開發 Tkinter 應用程式時,我們經常遇到必須使用鍵盤按鍵(鍵盤上)執行某些特定操作或事件的情況。Tkinter 為處理此類事件提供了一種機制。
你可以為要繫結的每個元件使用 bind(<Key>, callback) 函式,以執行特定型別的事件。每當我們將一個鍵與一個事件繫結時,無論何時按下某個相應的鍵,回撥事件就會發生。
示例
我們來看一個示例。使用 bind("", callback) 函式,我們還可以繫結所有數字鍵,以便在螢幕上顯示一條訊息,這樣,每當使用者按下某個鍵(1-9)時,都會在螢幕上出現一條訊息。
# Import required libraries
from tkinter import *
# Create an instance of tkinter window
win = Tk()
win.geometry("700x300")
# Function to display a message whenever a key is pressed
def add_label(e):
Label(win, text="You have pressed: " + e.char, font='Arial 16 bold').pack()
# Create a label widget
label=Label(win, text="Press any key in the range 0-9")
label.pack(pady=20)
label.config(font='Courier 18 bold')
# Bind all the number keys with the callback function
for i in range(10):
win.bind(str(i), add_label)
win.mainloop()輸出
執行上述程式碼段將顯示一個帶有一個 Label 元件的視窗。

每當你在 (0-9) 範圍內按下某個鍵,它就在螢幕上顯示一條訊息。

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP