2

I am coding a client for a tic-tac-toe variant. The game logic changes are not relevant to this question

I am trying to show a 'hash-tag' tic-tac-toe grid like the one below.

grid example

I initially thought of using borders on the buttons, or the frames containing the buttons, but other questions found difficulty (and a couple of complicated workarounds) when adding borders to specific sides.

I would rather not resort to a Canvas object for drawing the game, since this feels - as do the others mentioned - like a cheap workaround at the expense of readability.

How can I add these lines in between frames/grid columns/labels/buttons?

speedstyle
  • 142
  • 4
  • 11

2 Answers2

3

You can do this by putting white frames inside a black one and using the padx and pady arguments of grid:

import tkinter as tk 

root = tk.Tk()

frame = tk.Frame(root, bg='black')
frames = []
for i in range(3):
    frames.append([])
    for j in range(3):
        frames[i].append(tk.Frame(frame, bg='white', width=50, height=50))
        frames[i][j].grid(row=i, column=j, 
                          padx=((j != 0) * 2,  (j != 2) * 2),
                          pady=((i != 0) * 2,  (i != 2) * 2))

frame.pack()
root.mainloop()

padx and pady can either take a single number to get a symmetrical result or a tuple of values:padx=(<left>, <right>) and pady=(<top>, <bottom>).

screenshot

j_4321
  • 15,431
  • 3
  • 34
  • 61
0

What about something like this:

# I use python 2
import Tkinter as tk 
# For Python 3 use import tkinter as tk 

def create_grid(event=None):
    w = c.winfo_width() # Get current width of canvas
    h = c.winfo_height() # Get current height of canvas
    c.delete('grid_line') # Will only remove the grid_line

    # Creates all vertical lines at intevals of 100 except for first and last
    for i in range(100, w - 100, 100):
        c.create_line([(i, 0), (i, h)], tag='grid_line')

    # Creates all horizontal lines at intevals of 100 except for first and last
    for i in range(100, h - 100, 100):
        c.create_line([(0, i), (w, i)], tag='grid_line')

root = tk.Tk()

c = tk.Canvas(root, height=300, width=300, bg='white')
c.pack(fill=tk.NONE, expand=True)

c.bind('<Configure>', create_grid)

root.mainloop()

I took this answer and tweaked it a bit so the edges won't be shown

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • In the question, I said *I would rather not use a `Canvas` object for drawing the game* – speedstyle Feb 02 '18 at 06:45
  • 2
    @speedstyle When someone answers the question you'vee asked, they're not necessarily answering only your question but the questions future researchers may ask. I think this answer may be useful to future visitors searching on how to have gridlike layout. – Nae Feb 02 '18 at 14:26
  • True; apologies. – speedstyle Feb 02 '18 at 17:10