如何繫結 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