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.

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

Examples

1. Create Button in 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() 

Explanation

  1. The tkinter library is imported, which is used for creating GUI applications in Python.
  2. A Tk object gui is created, which represents the main window of the application. The window is given the title 'Python Examples - Button', and its size is set to 500x200 pixels using the geometry() method.
  3. A Button widget is created with the following properties:
    • text='My Button': Sets the text displayed on the button.
    • width=40, height=3: Specifies the width and height of the button.
    • bg='#0052cc', fg='#ffffff': Sets the background and foreground colors of the button.
    • activebackground='#0052cc', activeforeground='#aaffaa': Defines the button's colors when it is clicked (active state).
  4. The button.pack() method is used to add the button to the window and position it.
  5. Finally, gui.mainloop() is called to start the tkinter event loop, allowing the window to be displayed and interactive.

Output

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.




Python Libraries