Search code examples
pythontkintercanvas

How to insert grid system to place label and more in rows and columns?


how can I insert a grid system with rows and columns to place the labels, insert boxes and buttons? instead of entering them with x,y coordinates.

For example, in this case, I have to insert label1 with the cordinates x,y.

What should i change? thanks to those who will answer me.

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("title of window")
root.geometry('1230x720')
root.resizable(False, False)

bg = PhotoImage(file="/Users/file.png")
my_canvas = Canvas(root, width=1000, height=720)
my_canvas.pack(fill='both', expand=True)

label1 = my_canvas.create_text(500, 30,
                               text='hello world',
                               fill='Black',
                               font=('Helvetica Bold', 24),
                               anchor='w')

root.mainloop()

Solution

  • If I'm not mistaken, there aren't grid property for Canvas object. The best you can do is to create grid for the entire root, and set rowspan, columnspan for it. It might look like this:

    from tkinter import *
    from tkinter import ttk
    
    root = Tk()
    root.title("title of window")
    root.geometry('1230x720')
    root.resizable(False, False)
    
    bg = PhotoImage(file="/Users/file.png")
    my_canvas = Canvas(root, width=1000, height=720)
    my_canvas.grid(row=0, column=0, rowspan=10, columnspan=10)  # Important part
    my_canvas.create_image(0, 0, image=bg, anchor='nw')
    
    label1 = Label(text='hello world', fg='black', font=('Helvetica Bold', 24))
    label1.grid(row=0, column=0)
    label2 = Label(text='hi world', fg='black', font=('Helvetica Bold', 24))
    label2.grid(row=1, column=0)
    label3 = Label(text='greeting world', fg='black', font=('Helvetica Bold', 24))
    label3.grid(row=0, column=1)
    
    root.mainloop()