使用按鈕或按鍵呼叫 Tkinter 中的功能
我們假設我們希望在為特定應用程式按下一個按鈕或鍵時呼叫某個函式。我們可以使用 bind('<button or Key>,' callback_function) 方法將包含操作的函式與一個按鈕或鍵繫結。在這裡,你可以將任意鍵繫結到需要呼叫的事件或函式。
示例
在這個示例中,我們建立了一個函式,它將在我們點選一個按鈕時開啟一個對話方塊。
#Import the required libraries from tkinter import * from tkinter import ttk from tkinter import messagebox #Create an instance of Tkinter Frame win = Tk() #Set the geometry of Tkinter Frame win.geometry("700x350") #Define a function for opening the Dialog box def open_prompt(): messagebox.showinfo("Message", "Click Okay to Proceed") #Create a Label widget Label(win, text= "Click to Open the MessageBox").pack(pady=15) #Create a Button for opening a dialog Box ttk.Button(win, text= "Open", command= open_prompt).pack() win.mainloop()
輸出
執行上面的程式碼將顯示一個包含標籤和按鈕的視窗。
單擊“開啟”按鈕後,它將呼叫一個函式來開啟一個對話方塊。
廣告