tkinter
  1. tkinter-button

Button - Basic Tkinter Widgets

In Tkinter, a button is a basic widget used for clicking and performing some action. A button is a rectangular-shaped object with a label and an optional image on it.

Syntax

The basic syntax for creating a button in Tkinter is as follows:

my_button = Button(parent, text='Click me', command=my_function, ...)

Here, parent is the parent widget where the button will be placed, text is the label of the button, command is the function to be executed when the button is clicked, and ... represents other optional parameters, such as height, width, fg, bg, etc.

Example

Consider the following example, where a button is created and placed in the root window:

import tkinter as tk

root = tk.Tk()

def hello():
    print("Hello World!")

my_button = tk.Button(root, text="Click me", command=hello)
my_button.pack()

root.mainloop()

In this example, a button is created with the label "Click me" and the function hello is called when the button is clicked. The pack() method is used to place and display the button.

Output

When the above code is executed, a window will open with a button labeled "Click me". When the button is clicked, the string "Hello World!" will be printed in the console.

Explanation

The Button widget creates a standard Tkinter button that performs a specific action when clicked. When the button is clicked, the assigned function is executed.

In the example above, a button is created using the Button constructor with the text "Click me" and the function hello is assigned to its command parameter. When the button is clicked, the hello function is called and the string "Hello World!" is printed in the console using the print() function. Finally, the pack() method is used to place and display the button in the root window.

Use

Buttons are commonly used in Tkinter to trigger some specific action. They are one of the most basic and frequently used widgets in Tkinter programming. They can be used in various GUI applications like games, calculators, web browsers, etc.

Important Points

  • Buttons can have a name, label, or image on them.
  • Buttons in Tkinter are rectangular-shaped by default. But, you can achieve different shapes using the canvas widget.
  • Buttons can be disabled or enabled using the state parameter.
  • The Button widget has many optional parameters like height, width, bg, fg, font, etc. that controls the appearance of the button.

Summary

In Tkinter, a button is a basic widget used for clicking and performing some action. The Button widget creates a rectangular-shaped object with a label and an optional image on it. Buttons are one of the most basic and frequently used widgets in Tkinter programming. Buttons can be customized in various ways using numerous parameters provided with the Button constructor.

Published on: