我试图在Tkinter中创建一个TicTacToe游戏,我试图把一个标签放在棋盘的按钮下,但是当我把标签放在按钮下时,按钮会移动到一边。这是我的代码:
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()
当您尝试在按钮下面添加标签时,如果您不指定列跨度,标签将占据整个单元格,所以发生的是标签比按钮宽,因为它占据了所有的单元格,按钮转到了侧面,所以如果你这样说:
...
space.grid(row=3, column=0)
messages.grid(row=4, column=0, columnspan=3)
root.mainloop()
您正在告诉tkinter您的标签占用了三列,因此它不再移动按钮。结果如下: