Tkinter: Basic GUI Widgets Elements with Python Example
Graphical user interface with tkinker python library
--
In the previous article, we read about the basic idea of tkinker, if you want to read that article, the link is here.
This article will cover mostly the widgets of the tkinter. Widgets are the different types of instances through which we interface with operating system functionality by adding buttons, labels, menus, and other elements.
Creating a Simple Button
In this widget, we will create a button and give the functionality to close the root window after clicking on the button.
Example
# Importing the tkinker library
from tkinter import *
# creating an object to get the root window
root = Tk()
# Window size of the tkinter
root.geometry('200x100')
# button creation with close function on clicking
button = Button(root, text = 'Click me !', bd = '5',
command = root.destroy)
# the pack method used to give the position of the button
button.pack(side = 'top')
root.mainloop()
Output
Creating button with Image
In this widget, we will insert an image with the text to enhance the visual of the button. In this example, we are not giving the close functionality on the button.
Example
# importing the necessary libraries
from tkinter import *
from tkinter.ttk import *
# creating an object to get the root window
root = Tk()
# this label method is used to add the label in the window
Label(root, text = 'This is Button with image', font =(
'Ariel', 10)).pack(side = LEFT, pady = 10)
# giving the path of the image
photo = PhotoImage(file = r"index.png")
# this method is to resize the image we are adding
photoimage = photo.subsample(3, 3)
# the button method uses the image parameter to add the image in
# the button
Button(root, text = 'Click Me !', image = photoimage,
compound = LEFT).pack(side = TOP)
mainloop()
Output
Creating labels
In this type, we will create labels in the frame where we can show text and images.