Ad

Python Tkinter Grid Inside Grid?

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)]
Ad

Answer

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 r in range(4):
    for c in range(4):
        
        f = tk.Frame(root)
        f.grid(row=r, column=c, padx=5, pady=5)
        
        for ir in range(3):
            for ic in range(3):
                MyMap(f, ir, ic, ir*3+ic)

root.mainloop()               

enter image description here

Ad
source: stackoverflow.com
Ad