確定在 Tkinter 中按下了哪個按鈕
按鈕在需要使用者互動的許多應用程式中非常有用。我們假設想了解在給定應用程式中按下了哪個按鈕。為了獲取有關按鈕的資訊,可以在按鈕配置中使用回撥函式。在回撥函式中,我們將使用 print(test) 函式以列印所點選的按鈕。
示例
#Import the required libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter Frame
win = Tk()
#Set the geometry
win.geometry("700x250")
# Define function to get the information about the Button
def get_button(t):
print(t)
#Create Button Object
b1= ttk.Button(win, text= "Button-1", command= lambda t= "Button-1 Clicked": get_button(t))
b1.place(relx= .46, rely= .5, anchor= CENTER)
b2= ttk.Button(win, text= "Button-2", command= lambda t= "Button-2 Clicked": get_button(t))
b2.place(relx= .58, rely= .5, anchor= CENTER)
win.mainloop()輸出
執行以上程式碼將顯示一個帶有兩個按鈕的視窗。

如果你點選“Button-1”,它將在控制檯中列印以下內容。
Button-1 Clicked
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP