The Button widget in Tkinter allows you to add buttons to a Python application. You can customize the appearance of the button and associate a function to execute when the button is pressed.
W = Button(parent, options)
Here, parent refers to the parent widget (like the main application window), and options are the various settings used to configure the button.
| SN | Option | Description |
|---|---|---|
| 1 | activebackground | Background color when the mouse hovers over the button. |
| 2 | activeforeground | Font color when the mouse hovers over the button. |
| 3 | bd | Border width of the button in pixels. |
| 4 | bg | Background color of the button. |
| 5 | command | The function or method called when the button is pressed. |
| 6 | fg | Foreground (text) color of the button. |
| 7 | font | Font used for the button text. |
| 8 | height | Height of the button (text lines for text buttons or pixels for image buttons). |
| 9 | highlightcolor | The color of the button highlight when it has focus. |
| 10 | image | Sets an image to be displayed on the button. |
| 11 | justify | Alignment of multiple lines of text: LEFT, RIGHT, or CENTER. |
| 12 | padx | Additional padding in the horizontal direction. |
| 13 | pady | Additional padding in the vertical direction. |
| 14 | relief | Type of the button border: SUNKEN, RAISED, GROOVE, or RIDGE. |
| 15 | state | Button state: DISABLED makes the button unresponsive, ACTIVE makes it interactive. |
| 16 | underline | Underlines the text of the button. |
| 17 | width | Width of the button (number of letters for text buttons, or pixels for image buttons). |
| 18 | wraplength | Wraps the text if it exceeds the given length, specified as a positive number. |
from tkinter import *
# Create the main window
root = Tk()
# Function to be called when button is clicked
def on_button_click():
print("Button clicked!")
# Create a button widget
button = Button(root, text="Click Me!", command=on_button_click, bg="lightblue", fg="black", padx=20, pady=10)
# Place the button in the window
button.pack()
# Run the application
root.mainloop()
In this example:
• A button labeled "Click Me!" is created.
• The command option is set to on_button_click, which is a function that prints a message to the console when the button is clicked.
• Additional customization includes the button's background color (bg), text color (fg), and padding (padx,pady).
You can modify the button's appearance and behavior by using different options depending on your application's needs.