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 to create 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.

Option Value
text The text displayed as Button Label
width To set the width of the button
height To set the height of the button
bg To set the background color of the button
fg To set the font color of the button label
activebackground To set the background color when button is clicked
activeforeground To set the font color of button label when button is clicked
command To call a function when the button is clicked
font To set the font size, style to the button label
image To set the image on the button

Examples

1. Create Button in Tkinter

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

text “My Button”
width 40
height 3
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.

Summary

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

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us