Image Widget in Tkinter (GUI Programming) – Python Tkinter Tutorial
Image Widget in Tkinter Python provides a vast number of libraries for GUI application development. Tkinter is the widely used library for GUI application development. Using Tkinter library of python which carries large numbers of widgets, we can easily create a Graphical User Interface for our application.
Image Widget: In Tkinter, image widget is used to display or add image icons on application window. It supports image file formats, including PNG, JPEG and GIF. We can also set width and height options to set the Label size for an image.
Syntax:
path = PhotoImage(file="path_of_image") label_image = Label(root, image=path)
Explanation:
- Images are used as a label. We have defined path variable for setting the url or path of the image and then later we assigned that image to our label widget.
- Note: If you are using separate directory for storing the images, then use path as dir/file.png etc.
Let’s see one example to understand this concept better
Example 1:
from tkinter import * from tkinter import ttk root = Tk() label = Label(root, text="This is Image").pack(side=TOP, pady=10) path = PhotoImage(file="icon/bulb.png") label_image = Label(root, image=path,width=400, height=400) label_image.pack() root.geometry("600x440") root.title("PythonLobby.com") root.mainloop()
Output:
Explanation:
- First, we have imported all the required libraries and modules of Tkinter using import *.
- Then we have initialized root as an object for Tk() class for creating a root window.
- Next we have added label widget in our application window.
- In the very next line we initialized path variable as the object of PhotoImage to carry the file location of our image file.
- Also in the next line we integrated our image file or path variable with label widget.
- Rest below code is used for configuring the dimensions and title of the application window.
This is all about the image widget in Tkinter. Actually there is no any widget for images in Tkinter. But this is an approach for setting label widget with an image.