Python tkinter Button Example

Python tkinter Button

When you are building a GUI application, button is one the building block that makes your application interactive.

In this tutorial, we shall learn how to implement Button in Python GUI using tkinter Python library.

Syntax – tkinter Button

The syntax to add a Button to the tkinter window is:

 mybutton = Button(master, option=value)
 mybutton.pack()

Where master is the window to which you would like to add this button. tkinter provides different options to the button constructor to alter its look.

OptionValue
textThe text displayed as Button Label
widthTo set the width of the button
heightTo set the height of the button
bgTo set the background color of the button
fgTo set the font color of the button label
activebackgroundTo set the background color when button is clicked
activeforegroundTo set the font color of button label when button is clicked
commandTo call a function when the button is clicked
fontTo set the font size, style to the button label
imageTo set the image on the button

Example 1: Button using tkinter

In the following example, we will create a tkinter button with the following properties.

text“My Button”
width40
height3
bg‘#0052cc’
fg‘#ffffff’
activebackground‘#0052cc’
activeforeground‘#aaffaa’

Python Program

from tkinter import *

gui = Tk(className='Python Examples - Button')
gui.geometry("500x200")

# create button
button = Button(gui, text='My Button', width=40, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa')
# add button to gui window
button.pack()

gui.mainloop() 

When you run this python program, you will get the following Window.

Python Button Example

Summary

In this tutorial of Python Examples, we learned how to create a GUI button in Python using tkinter.