如何在 Tkinter 中將按鍵繫結到按鈕?
Tkinter 提供了一種將小部件繫結到某些操作的方式。這些操作在特定小部件可以呼叫的函式中定義。bind(<button>, function()) 方法用於繫結鍵盤鍵以處理此類操作。我們還可以將特定鍵繫結為按鈕小部件處理某些事件。
示例
#Import tkinter library from tkinter import * from tkinter import ttk #Create an instance of Tkinter frame or window win = Tk() #Set the geometry of tkinter frame win.geometry("750x250") def callback(): Label(win, text="Hello World!", font=('Georgia 20 bold')).pack(pady=4) #Create a Label and a Button widget btn = ttk.Button(win, text="Press Enter to Show a Message", command= callback) btn.pack(ipadx=10) win.bind('<Return>',lambda event:callback()) win.mainloop()
輸出
執行以上程式碼將顯示一個包含按鈕的視窗。
當我們按下“Enter”鍵時,它將在螢幕上顯示訊息。
廣告