如何在 Tkinter 中处理按钮单击事件?
tkinterpythongui-programming更新于 2023/12/7 13:11:00
有时,处理 Tkinter 应用程序中的事件对我们来说可能是一项艰巨的任务。我们必须管理在运行应用程序时需要执行的操作和事件。Button 小部件对于处理此类事件很有用。我们可以使用 Button 小部件通过在命令中传递回调来执行特定任务或事件。
在向 Button 小部件发出命令时,我们可以有一个可选的 lambda 或匿名函数,它们解释为忽略程序中的任何错误。它们就像一个通用函数,但它们没有任何函数体。
示例
在此示例中,我们将创建一个按钮并传递函数以在窗口上显示弹出消息。
# Import the required libraries from tkinter import * from tkinter import messagebox from tkinter import ttk # Create an instance of tkinter frame win= Tk() # Set the size of the tkinter window win.geometry("700x350") # Define a function to show the popup message def show_msg(): messagebox.showinfo("Message","Hey There! I hope you are doing well.") # Add an optional Label widget Label(win, text= "Welcome Folks!", font= ('Aerial 17 bold italic')).pack(pady= 30) # Create a Button to display the message ttk.Button(win, text= "Click Here", command=show_msg).pack(pady= 20) win.mainloop()
输出
运行上述代码将显示一个带有按钮小部件的窗口。当我们单击按钮时,它将触发一个事件发生。
现在,单击按钮以查看在屏幕上显示弹出消息的事件。