I am trying to create a TicTacToe game in Tkinter and I am trying to put a label under the buttons of the board but when I am put the label under the buttons the buttons are moving to the sides. how can I fix it? this is my code:
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title('TicTacToe')
# X starts
clicked = True
count = 0
#button clicked function
def b_click(b):
global clicked
global count
if b["text"] == " " and clicked == True:
b["text"] = "X"
clicked = False
count = 1
elif b["text"] == " " and clicked == False:
b["text"] = "O"
clicked = True
count = 1
else:
messages["text"] = "you cant do that"
#build the buttons
b1 = Button(root, text=" ", font =("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command= lambda:b_click(b1))
b2 = Button(root, text=" ", font =("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command= lambda:b_click(b2))
b3 = Button(root, text=" ", font =("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command= lambda:b_click(b3))
b4 = Button(root, text=" ", font =("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command= lambda:b_click(b4))
b5 = Button(root, text=" ", font =("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command= lambda:b_click(b5))
b6 = Button(root, text=" ", font =("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command= lambda:b_click(b6))
b7 = Button(root, text=" ", font =("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command= lambda:b_click(b7))
b8 = Button(root, text=" ", font =("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command= lambda:b_click(b8))
b9 = Button(root, text=" ", font =("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command= lambda:b_click(b9))
messages = Label(root, text="", font =("Helvetica", 20), height=1, width=15, relief="sunken")
space = Label(root, text="", font =("Helvetica",))
#display the buttons
b1.grid(row=0, column=0)
b2.grid(row=0, column=1)
b3.grid(row=0, column=2)
b4.grid(row=1, column=0)
b5.grid(row=1, column=1)
b6.grid(row=1, column=2)
b7.grid(row=2, column=0)
b8.grid(row=2, column=1)
b9.grid(row=2, column=2)
space.grid(row=3, column=0)
messages.grid(row=4, column=1)
root.mainloop()
CodePudding user response:
When you try to add the label under the buttons, if you don't specify the columnspan the label will take the whole cell, so what happened is that the label is wider than the buttons, and since it took all the cell the buttons went to the sides, so if you put it like this:
...
space.grid(row=3, column=0)
messages.grid(row=4, column=0, columnspan=3)
root.mainloop()
you are telling tkinter that your label is taking the three columns, and so it does not move the buttons anymore. Here's the result: