【发布时间】:2021-11-17 07:42:43
【问题描述】:
我正在尝试在 Tkinter 中创建一个井字游戏,我正在尝试在板的按钮下方放置一个标签,但是当我将标签放在按钮下方时,按钮会移动到两侧。 我该如何解决? 这是我的代码:
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()
【问题讨论】:
-
我认为
messages是您遇到问题的标签。由于它只存在于第 1 列,它不能延伸到第 0 列的按钮下方,也不能延伸到第 2 列的按钮下方;它所能做的就是把它们推到一边。您希望它能够使用所有三列的空间 - 例如column=0, columnspan=3。或者,您可以将所有按钮放在一个框架内;然后,您可以将小部件直接放在该框架之外的根窗口中,这样它们就不会受到应用于按钮的网格的约束。