How to Create Buttons in Python with Tkinter?

In this tutorial, I will explain how to create buttons in Python with Tkinter. As a developer based in the USA, I’ve encountered many scenarios where incorporating functional and visually appealing buttons was crucial for enhancing the user experience. In this article, we’ll dive deep into the process of creating and customizing buttons using Tkinter, addressing common challenges and providing practical examples.

Tkinter Button Widget

The Tkinter Button widget is a graphical control element used in Python’s Tkinter library to create clickable buttons in a graphical user interface (GUI). Buttons can display text or images that convey the purpose of the button and trigger specific functions or actions when clicked.

To create a button in Tkinter, you need to follow these basic steps:

  1. Import the Tkinter module
  2. Create a window or frame to hold the button
  3. Create an instance of the Button widget
  4. Configure the button’s properties (text, size, color, etc.)
  5. Place the button in the desired location within the window or frame

Here’s a simple example that demonstrates the creation of a button:

import tkinter as tk

def button_click():
    print("Button clicked!")

window = tk.Tk()
window.title("Button Example")

button = tk.Button(window, text="Click Me", command=button_click)
button.pack()

window.mainloop()

I have executed the above example code and added the screenshot below.

Create Buttons in Python with Tkinter

In this example, we create a window using tk.Tk() , set its title to “Button Example”, and then create a button with the text “Click Me”. The command parameter is set to the button_click function, which will be called whenever the button is clicked. Finally, we use button.pack() to place the button in the window and start the main event loop with window.mainloop().

Read How to Create Radio Buttons in Python with Tkinter?

Customize Button Appearance

Tkinter allows you to customize various aspects of a button’s appearance to match your application’s design. Here are some common properties you can modify:

  • text: The text displayed on the button.
  • font: The font style and size of the button text.
  • fg (foreground): The color of the button text.
  • bg (background): The background color of the button.
  • width and height: The size of the button in characters (width) or pixels (height).
  • padx and pady: The padding around the button text.
  • relief: The border style of the button (e.g., flat, raised, sunken).

Let’s see an example that customizes a button’s appearance:

import tkinter as tk

window = tk.Tk()
window.title("Custom Button")

button = tk.Button(window, text="Submit", font=("Arial", 14), 
                   fg="white", bg="green", width=10, height=2,
                   padx=10, pady=5, relief=tk.RAISED)
button.pack()

window.mainloop()

I have executed the above example code and added the screenshot below.

How to Create Buttons in Python with Tkinter

In this example, we create a button with the text “Submit” and customize its font, foreground color, background color, size, padding, and border style. The resulting button will have a blue background, white text, Arial font with size 14, a width of 10 characters, a height of 2 lines, 10 pixels of horizontal padding, 5 pixels of vertical padding, and a raised border style.

Read How to use Tkinter Filedialog in Python

Handle Button Events

The primary purpose of buttons is to trigger specific actions or events when clicked. Tkinter allows you to associate functions or methods with button clicks using the command parameter.

Here’s an example that demonstrates handling a button click event:

import tkinter as tk

def greet():
    name = name_entry.get()
    greeting_label.config(text=f"Hello, {name}!")

window = tk.Tk()
window.title("Greeting App")

name_label = tk.Label(window, text="Enter your name:")
name_label.pack()

name_entry = tk.Entry(window)
name_entry.pack()

greet_button = tk.Button(window, text="Greet", command=greet)
greet_button.pack()

greeting_label = tk.Label(window, text="")
greeting_label.pack()

window.mainloop()

I have executed the above example code and added the screenshot below.

Create Buttons in Python with Tkinter event

When the “Greet” button is clicked, the greet() function is called. It retrieves the name entered by the user name_entry.get() and updates the text of the greeting_label using greeting_label.config(text=...) to display a personalized greeting.

Read Expense Tracking Application Using Python Tkinter

Work with Button States

Tkinter buttons can have different states, such as normal, active, or disabled. You can control the state of a button using the state parameter.

  • normal: The default state where the button is clickable and responsive.
  • active: The state when the button is being clicked or hovered over.
  • disabled: The state where the button is unclickable and appears grayed out.

Here’s an example that demonstrates changing the state of a button:

import tkinter as tk

def toggle_button_state():
    if button["state"] == tk.NORMAL:
        button.config(state=tk.DISABLED)
    else:
        button.config(state=tk.NORMAL)

window = tk.Tk()
window.title("Button State Example")

button = tk.Button(window, text="Click Me", command=toggle_button_state)
button.pack()

window.mainloop()

I have executed the above example code and added the screenshot below.

Create Buttons in Python with Tkinter Button States

In this example, we create a button that toggles its state between normal and disabled when clicked. The toggle_button_state() function checks the current state of the button button["state"] and toggles it accordingly using button.config(state=...).

Read Python Tkinter Separator + Examples

Retrieve Button Text

In some cases, you may need to retrieve the text of a specific button. Tkinter provides the cget() method to access the properties of a widget, including the button text.

Here’s an example that demonstrates retrieving the text of a button:

import tkinter as tk

def show_button_text():
    button_text = button.cget("text")
    print(f"Button text: {button_text}")

window = tk.Tk()
window.title("Button Text Example")

button = tk.Button(window, text="Press Me", command=show_button_text)
button.pack()

window.mainloop()

I have executed the above example code and added the screenshot below.

Create Buttons in Python with Tkinter get button text

In this example, when the button is clicked, the show_button_text() function is called. It retrieves the text of the button button.cget("text") and prints it to the console.

Read How to Generate Payslip using Python Tkinter + Video Tutorial

Tkinter Button Styles

To create stylish buttons in Tkinter, you can use the ttk (themed Tk) module, which provides a set of themed widgets with enhanced styling capabilities. Here’s a brief explanation of how to apply styles to Tkinter buttons using ttk:

  1. Import the necessary modules:
import tkinter as tk
from tkinter import ttk
  1. Create a style object:
style = ttk.Style()
  1. Configure the style for the button:
style.configure("TButton", foreground="white", background="blue", font=("Arial", 12), padding=10)
  1. Create a button using the styled button class:
button = ttk.Button(window, text="Click Me", style="TButton")

Here, we create a button using ttk.Button and apply the “TButton” style to it.

  1. Pack the button and start the main event loop:
button.pack()
window.mainloop()

Here’s a complete example that demonstrates styling Tkinter buttons using ttk:

import tkinter as tk
from tkinter import ttk

window = tk.Tk()
window.title("Styled Button Example")

style = ttk.Style()
style.configure("TButton", foreground="Black", background="blue", font=("Arial", 12), padding=10)

button = ttk.Button(window, text="Click Me", style="TButton")
button.pack()
window.mainloop()

I have executed the above example code and added the screenshot below.

Create Buttons in Python with Tkinter style button

In this example, we create a window, define a style named “TButton” with specific properties, create a button using ttk.Button the “TButton” style applied, and pack the button in the window. You can further customize the button styles by modifying additional properties such as relief, width, height, and more.

Read How to convert Python file to exe using Pyinstaller

Tkinter Button Command

The button widget is used to place a button on the screen. The button holds a functionality that is triggered when pressed.

from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.title('Button example')

def subscribe():
    return messagebox.showinfo('USA Guide', 'Thank you for subscribing to the USA Guide!')

Button(ws, text="Subscribe", command=subscribe).pack(pady=20)

ws.mainloop()

I have executed the above example code and added the screenshot below.

Create Buttons in Python with Tkinter command

In this, there is a button Subscribe. When a user clicks on that button, a message box with the Thank you for subscribing to the USA Guide! appears.

Read Create Word Document in Python Tkinte

Tkinter Button Command Arguments

Command button argument refers to providing input in the command button. In a calculator, the code takes a key argument through a button command. Similarly, we will write code that will send a number to the function.

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('200x200')

ep = ''
def keyLog(k):
    global ep
    ep = ep + str(k)
    actn.set(ep)

actn = StringVar()
Entry(ws, textvariable=actn).pack()

one_Btn = Button(ws, text='1', command=lambda: keyLog(1), padx=5, pady=5)
two_Btn = Button(ws, text='2', command=lambda: keyLog(2), padx=5, pady=5)
three_Btn = Button(ws, text='3', command=lambda: keyLog(3), padx=5, pady=5)

one_Btn.pack()
two_Btn.pack()
three_Btn.pack()

ws.mainloop()

I have executed the above example code and added the screenshot below.

Create Buttons in Python with Tkinter Button Command Arguments

So in this output, the argument in the form of a key name ie. 1, 2, or 3 is passed to the function wherein these numbers are printed in the entry box.

Read Create Word Document in Python Tkinter

Tkinter Button Shape

Shape refers to applying a shape to the button. Shapes can be rectangular, oval, circular, etc. Shapes are not supported in Tkinter, you cannot create a rounded button directly from the widget. to do so you need a rounded image and then reduce the border width to 0. To see the demo refer to the Tkinter image section.

Read Python Tkinter Filter Function()

Tkinter Button Image

To apply an image on a button we use the image keyword

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x200')   

dwnd = PhotoImage(file='download.png')
Button(ws, image=dwnd, command=None).pack(pady=10)

ws.mainloop()

The Download button image is applied to the button widget. It is clickable which means it is a button. But this has a button background. To remove the button border set border width = 0.

Read Python Tkinter add function with examples

Tkinter Button Position

There are 3 layout managers: Pack, Grid, and Place. The pack is used to align widgets in the center of the frame. The grid uses the row & column method of placing widgets. The place is used to position widgets in any coordinated provided as x & y.

Syntax:

Button(ws, text="any text", command=function/method).pack()

Button(ws, text="any text", command=function/method).grid(row=value, column=value)

Button(ws, text="any text", command=function/method).place(x=value, y=value)

Code using pack:

from tkinter import *

ws = Tk()
ws.title("Pack")
ws.geometry('200x250')

Button(ws, text="Click", command=None).pack()

ws.mainloop()

In this output, a pack is used to place the button. Pack aligns the widget in the center. That is why when the screen is resized in the second picture, the button remains in the center position.

Code using grid:

from tkinter import *

ws=Tk()
ws.title("grid")
ws.geometry('200x250')

Button(ws,text="Click",command=None).grid(row=0, column=0)

ws.mainloop()

In this output, you can see that the button is positioned at 0 rows & 0 columns which means the top left side. In the grid, the button remains in its position even if the window is resized.

Code using place:

from tkinter import *

ws = Tk()
ws.title("place")
ws.geometry('200x250')

Button(ws, text="Click", command=None).place(x=20, y=20)

ws.mainloop()

In this output, buttons are positioned using the place. The place provides maximum control, 2 buttons are placed in different positions, but since the screen size is smaller than the position of the second button, it does not appear. But when the screen is stretched it starts appearing.

Read Python Tkinter panel

Conclusion

In this tutorial, I have explained how to create buttons in Python with Tkinter. I discussed how to customize button appearance, handle button events, work with button states , and retrieve button text. I also coved Tkinter button style, button command, button command argument, button shape, button image, and button position.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.