Home > front end >  Reversing a 2d grid so (0,0) is on the bottom left, instead of top left
Reversing a 2d grid so (0,0) is on the bottom left, instead of top left

Time:01-14

I have a 2d grid, where 0,0 is the top left corner of the grid. However, I need 0,0 to be the bottom left corner with the y axis increasing bottom to top.

for x in range(engine.map_size):
    for y in range(engine.map_size):
        self.columnconfigure(x, weight=1)
        self.rowconfigure(y, weight=1)

(this is inside a tkinter project)

This works fine but as stated, this places 0,0 at the top left corner. I tried using range with reversed(), and a range starting from engine.map_size-1 counting down, but that didn't seem to change anything

for x in range(engine.map_size):
    for y in range(engine.map_size, -1, -1):
        self.columnconfigure(x, weight=1)
        self.rowconfigure(y, weight=1)

I also tried the way above, which also produced no change

I left the tkinter code in there for context, but essentially I'm just trying to get the y range to descend from map_size to 0. Not 0 to map_size. Is range not the right choice here?

CodePudding user response:

The tkinter grid starts at the top-left, i.e. the 0th row is the top row, and the 0th column is the left column.

These loops you have simply configure the grid so that all rows and all columns have a weight of 1.

for x in range(engine.map_size):
    for y in range(engine.map_size, -1, -1):
        self.columnconfigure(x, weight=1)
        self.rowconfigure(y, weight=1)

I suspect you want to insert controls1 into different rows, so that the first row of your controls is inserted into the bottom row of the grid instead of the top.

total_rows = 4
total_cols = 4


labels = [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"]]

for row_num, row in enumerate(labels):
    for col_num, lbl_text in enumerate(row):
        lbl_control = ttk.Label(self, text=lbl_text)
        lbl_control.grid(column=col_num, row=total_rows - row_num - 1, ...)

Note that I add the control to the total_rows - row_num row. This makes sure that the 0th row of labels is added to the 3th (i.e. last) row of the grid.

1: Terminology I used in this answer could be wrong because I have no experience with tkinter

CodePudding user response:

if you use the function reversed(range(engine.map_size)). that would do the magic!

so your code would looks like:

for x in range(engine.map_size):
    for y in reversed(range(engine.map_size)):
        self.columnconfigure(x, weight=1)
        self.rowconfigure(y, weight=1)
  • Related