Introduction to Tkinter
Have you ever wondered how modern applications and programs are created? User-friendly Graphical User Interfaces (GUIs) are often used to allow you to interact with them.
Tkinter is one such library in the Python programming language that is widely used to create GUIs. In this article, we will explore the basics of Tkinter and how it works. What is Tkinter?
Tkinter is a library that allows developers to create Graphical User Interfaces (GUIs) with Python code. It is popular because it is included with Python’s standard library, making it readily available and easy to use.
Tkinter provides a set of tools that developers can use to build a variety of GUIs for various operating systems, including Windows, macOS, Linux, and more.
Advantages of using Tkinter
One of the significant advantages of using Tkinter is that it is cross-platform, which means that you can use it to create applications that will run on different operating systems. Furthermore, Tkinter is pre-installed with Python, making it very easy to set up and use.
This feature also means that the deployment process is more straightforward since users do not have to install additional libraries. Finally, Tkinter is platform-independent, making it an excellent choice for developers that need to create applications for different platforms.
Checking if Tkinter is working
Before creating a GUI, you need to ensure that Tkinter is installed and working correctly. Here is how you can check if Tkinter is working:
Running Python command to check if Tkinter is installed
Open your command prompt (Windows) or bash (macOS/Linux) and type the following command:
python -m tkinter
This command will start Tkinter and display a simple Tkinter window that confirms Tkinter is working correctly.
Output of the command
When you run the above command, you should see a blank window appear on your screen, indicating that Tkinter is working. The window should have a title of “Tk” and some basic features like a close button and a maximize button.
You can now use Tkinter to create your GUIs.
Conclusion
In this article, we have explored the basics of Tkinter and how you can check whether it is installed and working on your system. Tkinter is an incredibly useful library when it comes to creating Graphical User Interfaces for your Python applications.
As such, it is essential to have it set up correctly before you start building your GUIs. But now that you know how to check if Tkinter is working correctly, you can start creating your GUIs with ease.
Creating a Tkinter Canvas
Tkinter allows developers to create different types of widgets, which can be used to create a variety of GUIs. One of the most commonly used widgets is the Canvas widget, a blank area that developers can use to draw graphics, text, and other widgets. In this section, we will explore how to create a Tkinter Canvas.
Instantiating the Tkinter object
Before you can create a Tkinter Canvas, you need to create a Tkinter object. The Tkinter object is the master object that controls your application main window.
To create a Tkinter object, you instantiate the Tk() class in your Python script.
import tkinter as tk
root = tk.Tk()
root.mainloop()
The code above imports the Tkinter library, creates an instance of the Tk class and starts the mainloop. The mainloop pays attention to all the events happening on the window and takes necessary actions (e.g., responding to a button click, resizing of the window, etc.).
Creating a Canvas using the tk.Canvas() method
Now that you have instantiated the root object let’s create a Tkinter Canvas. A Canvas is a widget that you can use to draw graphics on a blank area.
You can create a canvas widget using the tk.Canvas() method.
canvas = tk.Canvas(root, background='white', width=500, height=500)
This line of code creates a Canvas widget with a white background.
It has a width of 500 pixels and a height of 500 pixels. Displaying the Canvas using canvas.pack()
To show the canvas on the screen, we use the pack() method to display the widget.
The pack() method adds the Canvas to the window automatically.
canvas.pack()
Creating an Application class to handle the master object
Creating all the GUI elements in one main script can result in convoluted code. A better way to organize your code is by creating a separate class that handles your GUI elements.
The following code demonstrates an Application class.
class Application:
def __init__(self, master):
self.master = master
self.canvas = tk.Canvas(self.master, background='white', width=500, height=500)
self.canvas.pack()
Creating an image item using tk.PhotoImage class
The Canvas widget also allows developers to add images to it.
First, you need to load the image into a PhotoImage object. You can create a PhotoImage object using the tk.PhotoImage() method.
photo = tk.PhotoImage(file="image.png")
The above code loads an image named “image.png” and stores it in the variable called “photo”. The PhotoImage method only supports GIF, PNG, and PPM/PGM formats.
Displaying the image on the Canvas using canvas.create_image()
To display the image on the Tkinter Canvas, you can use the create_image method. The create_image method creates a new image item on the Canvas.
image_x = 100
image_y = 200
canvas.create_image(image_x, image_y, anchor='nw', image=photo)
The `create_image()` method takes the coordinates of the location at which you want to place the image as arguments. The `anchor` argument is optional and specifies the point on the image used as a reference for its position; ‘nw’ stands for northwest.
The image parameter is the PhotoImage object that you want to display.
Creating an addImage() method to handle the image display
Rather than adding the image every time manually, we can create a method that adds the image to the canvas when it is called. The method should take the image filename and the coordinates as arguments.
class Application:
def __init__(self, master):
self.master = master
self.canvas = tk.Canvas(self.master, background='white', width=500, height=500)
self.canvas.pack()
def addImage(self, filename, direction):
photo = tk.PhotoImage(file=filename)
img = self.canvas.create_image(0, 0, anchor='nw', image=photo)
if direction == "right":
self.canvas.move(img, 5, 0)
elif direction == "left":
self.canvas.move(img, -5, 0)
# Fix garbage collection problem
self.img = photo
Fixing the image display issue using a reference to the image object
Tkinter’s PhotoImage object works a little differently than other image libraries like PIL. Tkinter does not keep a reference to the image object by default, which can result in the image disappearing after it is added to the canvas.
To fix this issue, we need to store a reference to the PhotoImage object.
self.img = photo
The code above creates an object that references the PhotoImage named “self.img”.
This keeps the PhotoImage object from being garbage collected by Python.
Conclusion:
In this section, we have learned how to create a Tkinter Canvas with a white background, display the Canvas on the Tkinter window using the pack() method, add an image to the Canvas by loading it into a tkinter PhotoImage object, and finally displaying the image using the create_image method. We’ve also created an addImage() method to handle the image display in a more efficient way.
Finally, we’ve fixed a problem of garbage collection by creating a reference to the PhotoImage object. In summary, this article has covered the basics of using Tkinter to create Graphical User Interfaces in Python.
We have explained what Tkinter is and its advantages, how to check if Tkinter is working correctly, and how to create a Tkinter Canvas with a white background. We have also explored how to add an image to the Canvas, create an addImage() method to handle image display, and fix the problem of garbage collection.
The importance of properly setting up Tkinter cannot be overstated, as it simplifies the process of creating user-friendly GUIs. The takeaways from this article are that Tkinter provides a set of useful tools that developers can use to create GUIs, that checking if Tkinter is properly installed is a crucial step, and that creating a separate class to handle GUI elements and properly referencing image objects can optimize your code.