如何根据使用tkinter和python的quixo游戏在按钮网格上的每个按钮上添加文本

问题描述 投票:0回答:1

我使用python为该quixo游戏创建GUI。但是我不需要在GUI上播放。只是为了显示玩家的动作

from tkinter import *

    root = Tk()
    root.title("QUIXO")

    for i in range(1,6):
        for j in range(1,6):

            myButton = Button(root, text="0", padx = 20, pady = 20)
            myButton.grid(row=i, column=j)


    root.mainloop()

我有这段代码可以制作5x5的按钮网格。我使用按钮是因为我不知道还有什么用。但是在这个网格上,我需要根据在quixo板上的位置加X和0。

基本上我有一个矩阵

作为示例

[[-,-,-,-,X]
[-,-,-,-,X]
[-,-,-,0,-]
[0,-,-,0,X]
[0,-,0,0,-]] 

如何将其放置在按钮的网格上?按钮不需要单击。只是在那里显示信息

python button tkinter grid
1个回答
0
投票

这就是我的方式,可能不是最优雅的解决方案:

from tkinter import *

root = Tk()
root.title("QUIXO")

buttonmatrix = [["" for i in range(5)] for i in range(5)] #Creates a 5x5 matrix with 0s as placeholders

#Then iterate through the matrix assigning buttons to each index and gridding them in the tkinter GUI

for i in range(5):
    for j in range(5):
        buttonmatrix[i][j]  = Button(root, text="0", state = "disabled", padx = 20, pady = 20)
        buttonmatrix[i][j].grid(row = i, column = j)

def updatebuttongrid(matrix):  #A function that updates the text of the buttons in the grid to a matrix passed to it.
    for i in range(5):
        for j in range(5):
            buttonmatrix[i][j].configure(text = str(matrix[i][j]))


example = [["-","-","-","-","X"],
["-","-","-","-","X"],
["-","-","-",0,"-"],
[0,"-","-","0","X"],
[0,"-",0,0,"-"]]

updatebuttongrid(example) #call the function whenever you want to update the GUI

root.mainloop()

让我知道这是否有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.