Tkinter GUI:用标签替换一行中的一个按钮而不改变行的大小。哪怕一毫米

Tkinter GUI: Replacing one button in a row with a label WITHOUT changing the size of the row. Even by a millimetre

我制作了一个游戏,其中有一个 10*10 的按钮网格。其中 10 个被随机选择为 "tanks"。如果单击坦克,按钮将替换为标签 "Hit!"。我遇到的问题是,一旦发生这种情况,该按钮的行就会比其他行稍长或稍短。我该如何阻止它?

button[hit] = Label(text="Hit!", padx=5.5)

如果我将 "padx" 设置为 5.4,那么它只会比其他行短一点,而不是长一点。

我试过中间带几个小数点的数字,但就是行不通。

from tkinter import *
import random

root = Tk()
button = [""] * 100
row = [""] * 10
tank = [""] * 10
showHit = Label(text="Hit!")
prevHits = []

for i in range(10):
    x = 3
    y = random.randint(0,9)
    tank[i] = "(" + str(x) + "," + str(y) + ")"
print(*tank)

def getPos(pos):
    global tank
    print(pos)
    for i in tank:
        if pos == i:
            print("Hit!")
            a = int(pos[1])
            b = int(pos[3])
            print(a, b)  
            hit = a*10# + b
            for i in range(10):
                button[hit].destroy()
                hit += 1
            hit = a*10
            for i in range(10):
                if hit != (a*10) + b and not hit in prevHits:
                    string = "(" + str(a) + "," + str(i) + ")"
                    button[hit] = Button(root, text=string, command=lambda pos=string: getPos(pos))
                    button[hit].pack(in_=row[a], side=LEFT)
                else:
                    button[hit] = Label(text="Hit!", padx=5.4)
                    button[hit].pack(in_=row[a], side=LEFT)
                    prevHits.append(hit)
                print(hit)
                hit += 1



for r in range(len(row)):
    row[r] = Frame(root)
    row[r].pack()
    print(row[r])


num = len(button)
for i in range(num):
    t = i
    t %= 10
    if t == 0:
        r +=1
    if r == 10:
        r = 0
    string = "(" + str(r) + "," + str(t) + ")"
    button[i] = Button(root, text=string, command=lambda pos=string: getPos(pos))
    r = i // 10
    button[i].pack(in_=row[r], side=LEFT)

mainloop()

我通过用 grid() 替换 pack() 解决了这个问题,因此删除了所有帧,而是在每行中放置 10 个按钮。我还设法改进了我的代码:

        for i in range(10):
                if not hit != (a*10) + b and not hit in prevHits:
                    button[hit] = Label(text="Hit!", padx=5.4)
                    button[hit].grid(row=a, column=b, sticky = W)
                    prevHits.append(hit)
                print(hit)
                hit += 1

现在我可以精确定位一个按钮并对其进行更改,而不必按特定顺序重写整行。