如何在 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) 范围内按下某个键,它就在屏幕上显示一条消息。

更新于: 2021 年 12 月 22 日

1 千次浏览

开启你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.