Creating a button in tkinter in Python

PythonServer Side ProgrammingProgramming

As a library for Python Tkinter offers many ways to create a button on the tkinter canvas. In this article we will see how we can create a tkinter button with normal tkinter module as well as how to get it without using the themed tkinter module.

Using tkinter

In the program below we first create a canvas and then apply the Button method to create a button. We import the entire tkinter module, so the themes get applied to the button we create.

Example

# import everything from tkinter module
from tkinter import *

# create canvas
canv = Tk()

# Open canvas
canv.geometry('200x150')

# Create a Button
btn = Button(canv, text='Welcome to Tkinter!', bd='5',
            command=canv.destroy)

# Set the button position.
btn.pack(side='top')

canv.mainloop()

Output

Running the above code gives us the following result −

Using tkinter.ttk

We repeat the above process but this time we also include the tkinter.ttk module. It does not have the border (bd) option but it provides a light blue highlight colour when the mouse is brought over the button.

Example

# import everything from tkinter module
from tkinter import *
from tkinter.ttk import *

# create a canvas
canv = Tk()


# Open a window
canv.geometry('200x150')

# Create a Button
btn = Button(canv, text='Welcome to Tkinter!',
            command=canv.destroy)

# Set the button position.

btn.pack(side='top')

canv.mainloop()

Output

Running the above code gives us the following result −


raja
Published on 26-Aug-2020 06:45:51
Advertisements