Home > front end >  Python Tkinter grid inside grid?
Python Tkinter grid inside grid?

Time:03-25

I am trying to create a 2d map, and each map cell has another 5x5 cell.

I am able to generate the following 2d map:

enter image description here

Inside each block, I would like to create another smaller 3x3 grid cells, such that in each block there would be something like this:

enter image description here

mymap.py:

from tkinter import *

class MyMap():
    def __init__(self, master, i, j):
        self.text = StringVar()
        self.label = Label(master, textvariable = self.text, height = 5, width = 11, relief = RIDGE, bg = "gray30", fg = "white", font = "Helvetica 12")
        self.label.grid(row = i, column = j, sticky = W, pady = 1)
        self.row = i
        self.col = j

main.py

master = Tk()

[[MyMap(master, i, j) for j in range(4)] for i in range(4)]

CodePudding user response:

You could crate grid 4x4 using Frames and in every frame you could put your MyMap in grid 3x3.

import tkinter as tk  # PEP8: `import *` is not preferred

class MyMap():
    def __init__(self, master, i, j, text='?'):
        self.text = tk.StringVar(master, value=text)
        self.label = tk.Label(master, textvariable=self.text, height=5, width=11, relief='ridge', bg="gray30", fg="white", font="Helvetica 12")
        self.label.grid(row=i, column=j, sticky='w', pady=1, padx=1)
        self.row = i
        self.col = j
        
root = tk.Tk()

for outer_row in range(4):
    for outer_col in range(4):
        
        f = tk.Frame(root)
        f.grid(row=outer_row, column=outer_col, padx=5, pady=5)
        
        for inner_row in range(3):
            for inner_col in range(3):
                text = inner_row*3   inner_col
                MyMap(f, inner_row, inner_col, text)

root.mainloop()

enter image description here

PEP 8 -- Style Guide for Python Code

  • Related