Home > Enterprise >  How to make a grid in python and center it?
How to make a grid in python and center it?

Time:05-31

So I'm trying to make a grid where I can input grades My code currently looks like this

This is picture of an program,I want to make an grid so there is an entry for each month and each category, something like an gradebook:

enter image description here

Code example

import tkinter as tk

window8 = tk.Tk()
window8.title('Grades')
window8.geometry('1920x1080')
lbl_mjeseciime = tk.Label(master=window8, text='Months')
lbl_mjeseciime.place(x=1000, y=100)
lbl_kategorije = tk.Label(text='Categories:', master=window8)
lbl_kategorije.place(x=450, y=200)
lbl_mjeseci = tk.Label(master=window8,text='9                    10                    11                    12                    1                    2                    3                    4                    5                    6')
lbl_mjeseci.place(x=700, y=200)
lbl_kategorija1 = tk.Label(master=window8, text='Category1')
lbl_kategorija2 = tk.Label(master=window8, text='Category2')
lbl_kategorija1.place(x=450, y=300)
lbl_kategorija3 = tk.Label(master=window8, text='Category3')
lbl_kategorija2.place(x=450, y=450)
lbl_kategorija3.place(x=450, y=600)

window8.mainloop()

CodePudding user response:

You could use something like the following:

root = tk.Tk()

titles = ["Months", 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
number_of_months = 10
categories = ["Category1", "Category2", "Category3"]
entries = []

# Create headers for months
for n, t in enumerate(titles):
    tk.Label(root, text = str(t)).grid(row = 0, column = n)

# Create rows for categories
for n, r in enumerate(categories):
    # Create category text
    tk.Label(root, text = r).grid(row = n 1, column = 0)
    # Create list to store entries
    row_entries = []
    # Create an entry for each month
    for m in range(number_of_months):
        e = tk.Entry(root)
        row_entries.append(e)
        e.grid(row = n 1, column = m 1)
    entries.append(row_entries)

root.mainloop()

Instead of manually creating and placing each Label I've just made them in a loop instead. I've used grid to place the widgets as it allows you to easily place a widget in a row/column. I've also stored all of the entries in a 2d list entries so you can get their values at some point.

  • Related