Think about Tkinter Canvas as a place where we can have other shapes. That means that we need coordinates and dimensions.
In this case we will have red shape, which will be in primary, top_win, with 800 x 800 dimensions. Width will be 200 and height will be 200. As with other Tkinter elements, it's not enough to have something, we must position it.
In this example, we will use Grids to position elements. Think about Grids as Excel cells. Those cells are determined by intersection of rows and columns:
shape = Canvas(top_win, width = 200, height = 200, bg = "red")
shape.grid(row = 0, column = 0)
Full script with 3 basic shapes, positioned by grid options will be like this:
from tkinter import *
import tkinter.messagebox as mb
import os
top_win = Tk()
top_win.geometry("800x800")
shape = Canvas(top_win, width = 200, height = 200, bg = "red")
shape.grid(row = 0, column = 0)
shape_2 = Canvas(top_win, width = 200, height = 200, bg = "orange")
shape_2.grid(row = 1, column = 1)
shape_3 = Canvas(top_win, width = 200, height = 200, bg = "orangered")
shape_3.grid(row = 2, column = 2)
top_win.mainloop()
Also, we can have Canvases positioned by packing. In that case we need to think about sides and anchoring:
from tkinter import *
import tkinter.messagebox as mb
import os
top_win = Tk()
top_win.geometry("800x800")
shape = Canvas(top_win, width = 200, height = 200, bg = "red")
shape.pack(side = TOP, anchor = NW)
shape_2 = Canvas(top_win, width = 200, height = 200, bg = "orange")
shape_2.pack(side = RIGHT, anchor = NE)
shape_3 = Canvas(top_win, width = 200, height = 200, bg = "orangered")
shape_3.pack(side = BOTTOM, anchor = SW)
top_win.mainloop()
Another option is to experiment with pixels. Placing Canvases py pixels demands in most cases a little bit more time, but at the end of the day we can be happy with precision:
from tkinter import *
import tkinter.messagebox as mb
import os
top_win = Tk()
top_win.geometry("800x800")
shape = Canvas(top_win, width = 200, height = 200, bg = "red")
shape.place(x = 100, y = 100)
shape_2 = Canvas(top_win, width = 200, height = 200, bg = "orange")
shape_2.place(x = 150, y = 150)
shape_3 = Canvas(top_win, width = 200, height = 200, bg = "orangered")
shape_3.place(x = 300, y = 300)
top_win.mainloop()
No comments:
Post a Comment