如何绑定 Escape 键关闭 Tkinter 中的一个窗口?
Tkinter 事件对于使应用程序具有交互性和功能性非常有用。它提供了一种与应用程序的内部功能进行交互并帮助它们在执行单击或按键事件时触发的途径。
为了调度 Tkinter 中的事件,我们通常使用 bind('Button', callback) 方法。我们可以在应用程序中绑定任何键以执行某些任务或事件。要绑定Esc键以关闭应用程序窗口,我们必须在bind(key, callback)方法中将 Key 和回调事件作为参数传递。
示例
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define the style for combobox widget
style = ttk.Style()
style.theme_use('xpnative')
# Define an event to close the window
def close_win(e):
win.destroy()
# Add a label widget
label = ttk.Label(win, text="Eat, Sleep, Code and Repeat", font=('Times New Roman italic', 18), background="black", foreground="white")
label.place(relx=.5, rely=.5, anchor=CENTER)
ttk.Label(win, text="Now Press the ESC Key to close this window", font=('Aerial 11')).pack(pady=10)
# Bind the ESC key with the callback function
win.bind('<Escape>', lambda e: close_win(e))
win.mainloop()输出
运行以上代码会显示一个窗口,按“Esc”键立即关闭窗口。
现在按 <Esc> 键关闭窗口。
Advertisements
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP