Tuesday, April 22, 2025

Tkinter - Line, Oval, Arc, Rectangle

In last tutorial we mentioned that Canvas will be place where we can have multiple shapes.

First, we will establish Canvas with width of 500 and height of 500, with lightgreen background:

area = Canvas(top_win, width = 500, height = 500, bg = "lightgreen")

Then, we will have an orange rectangle with starting coordinates 10 and 10, with ending coordinates in x = 200 and y = 200:

rec = area.create_rectangle(10, 10, 200, 200, fill = "orange")

Why not have another, yellow rectangle, just for fun:

rec_2 = area.create_rectangle(20, 20, 150, 150, fill = "yellow")

To create an arc we will have something like this:

arc = area.create_arc(30, 30, 300, 300, extent = 223, fill = "red")

What about an oval ? No problem, it's easy:

oval = area.create_oval(10, 10, 300, 50, fill = "yellow")

 It's not enough to have Canvas, we must Grid it. In this case in a cell defined by 0 0 , which means upper top corner:

area.grid(row = 0, column = 0)

Full working source code:  

from tkinter import *
import tkinter.messagebox as mb
import os

top_win = Tk()
top_win.geometry("800x800")

area = Canvas(top_win, width = 500, height = 500, bg = "lightgreen")

rec = area.create_rectangle(10, 10, 200, 200, fill = "orange")
rec_2 = area.create_rectangle(20, 20, 150, 150, fill = "yellow")

arc = area.create_arc(30, 30, 300, 300, extent = 223, fill = "red")

oval = area.create_oval(10, 10, 300, 50, fill = "yellow")
    
area.grid(row = 0, column = 0)
top_win.mainloop()

Ok now we will have a bunch of lines. Their starting and ending coordinates will be randomly generated using random module. Don't forget to import it.

We will use for loop to generate lines:

for x in range(10):
    line = area.create_line(randrange(25, 100), randrange(25, 100),
                            randrange(50, 400), randrange(200, 400))

Full working script:

from tkinter import *
import tkinter.messagebox as mb
import os
from random import *

top_win = Tk()
top_win.geometry("800x800")

area = Canvas(top_win, width = 500, height = 500, bg = "lightgreen")

rec = area.create_rectangle(10, 10, 200, 200, fill = "orange")
rec_2 = area.create_rectangle(20, 20, 150, 150, fill = "yellow")

arc = area.create_arc(30, 30, 300, 300, extent = 223, fill = "red")

oval = area.create_oval(10, 10, 300, 50, fill = "yellow")

for x in range(10):
    line = area.create_line(randrange(25, 100), randrange(25, 100),
                            randrange(50, 400), randrange(200, 400))
    
area.grid(row = 0, column = 0)
top_win.mainloop()

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...