In this Python TKinter article i want to show you How To Create Canvas In Python TKinter. first let’s talk about TKinter Canvas, but before that let’s have a few words about TKinter, now if you are Python developer, then there are alot of Python libraries for GUI Development, now there will a question in your mind that What GUI is best for Python? among all of them TKinter is one the best library for building GUI Applications in Python.
What is Python Tkinter used for?
How to Create Canvas in Python TKinter?
Now let’s create our example on How to create a canvas in Tkinter? it is not hard and it is easy, This is the complete code for this article.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
from tkinter import * class Root(Tk): def __init__(self): super(Root, self).__init__() # Set title of the window self.title("Codeloop.org - Tkinter Canvas") # Set window icon self.iconphoto(True, PhotoImage(file='codeloop.png')) # Call method to create the canvas widget self.canvasWidget() def canvasWidget(self): # Create Canvas widget with blue background canvas = Canvas(self, bg="blue", height=250, width=300) # Define coordinates for an arc inside the Canvas coord = 10, 50, 240, 210 # Create an arc shape inside the Canvas arc = canvas.create_arc(coord, start=0, extent=150, fill="red") # Pack the Canvas widget into the window canvas.pack() # Create an instance of the Root class root = Root() root.mainloop() |
Now let’s describe the code:
Imports:
- We import the tkinter module to access its classes and functions.
1 |
from tkinter import * |
TKinter Root Class:
- We have defined a class Root that inherits from Tk, and it represents the main window of our Tkinter application.
- __init__ method initializes the window with a title and icon, then calls the canvasWidget method.
1 2 3 4 |
class Root(Tk): def __init__(self): super(Root, self).__init__() ... |
canvasWidget Method:
- This method creates a Canvas widget with specific attributes:
- Background color: blue
- Height: 250 pixels
- Width: 300 pixels
- It defines coordinates for an arc shape inside the Canvas.
- An arc shape is created inside the Canvas using specific coordinates, start angle, extent, and fill color.
- The Canvas widget is packed into the window.
1 2 |
def canvasWidget(self): ... |
Creating Application Instance and Running the Event Loop:
- An instance of the Root class is created.
- The Tkinter event loop is started (root.mainloop()), which listens for events such as button clicks and updates the GUI accordingly.
1 2 |
root = Root() root.mainloop() |
Run the complete code and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email