Creating a button in Tkinter

Creating a button in Tkinter

In this article, we will explore how to create a simple button in Tkinter. The button is used for a lot of user interaction and is often the most basic way to interact with a user. We will also cover some of the basics of how a Tkinter application is launched.

Setting up

After importing Tkinter we first create an application class from tk.Tk.  The super method inherits from the Tk class's init method. Note that we also passed an argument in the init method named button_text. The label of the button will have this text on it.

Creating the button

The init method also puts the button on the frame. Notice that the button will not be visible until we pack it or place it on the frame. The tk.Button creates the button. It accepts input such as text which defines what text the button should have. You can also create the button disabled by passing in the variable state="disabled" (use lower letter characters).  You can enable the button with "active". The button can also be created in different reliefs. The available reliefs are tk.GROOVE, tk.FLAT, tk.RIDGE. The normal state is TK.RAISED. When you push the button is shown in the state tk.SUNKEN.

Button up!

You can also pass an image to the button. Just create a button with tk.PhotoImage as below:

self.button_button_image = tk.PhotoImage(file="your_button_picture.png")

Then pass it with the variable image:

tk.Button(self, image = self.button_button_image, command=self.print_txt)

Finishing up

What we do next is creating a method for the button, which we call when we press the button. Next, we create a root frame and pass the text "My button" to label our button. We run the application with the mainloop method.

#! python3
# -*- coding: utf-8 -*-

import tkinter as tk

class button_tester_app(tk.Tk):
    def __init__(self, button_text):
        self._button_text = button_text
        # Create the button
        self.test_button = tk.Button(self, text = button_text, command=self.print_text)
        # Put the button to the frame
    def print_text(self):
        # Print the text to the console
        print("You pressed the \"{}\" test button!".format(self._button_text))
if __name__ == "__main__":
    root = button_tester_app("My button")

One comment on “Creating a button in Tkinter”

Leave a Reply

Your email address will not be published. Required fields are marked *

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram