In this example we will show how to handle a Button click event in tkinter.
The Button widget is useful for handling such events in Python Tkinter. We can use Button widget to perform a certain task or event by passing the callback in the command.
Examples
Example 1: In this example, we will create a button and pass the function to show a popup message on the window.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from tkinter import * from tkinter import messagebox root = Tk() root.title("App") root.geometry("200x100") def message(): messagebox.showinfo("Message :) ", "Hello, World!") button = Button( text="Click!", command=message ) button.pack() root.mainloop() |
Output:
Example 2: In this example, we will create a button, a label and pass the function to write a text in the label.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from tkinter import * root = Tk() root.title("App") root.geometry("200x100") def message(): label.config( text = "Hello World!" ) button = Button( text="Click!", command=message ) button.pack() label = Label( text="..." ) label.pack() root.mainloop() |
Output: