[英]How Do I add text on every button on a grid of buttons depending on a game of quixo using tkinter and python
I use python to create a GUI for this game of quixo.我使用 python 为这个 quixo 游戏创建 GUI。 but I dont need to play on the GUI.
但我不需要在 GUI 上玩。 just to show the players movements on it
只是为了向玩家展示它的动作
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()
I have this code which make the 5x5 grid of buttons.我有这段代码可以制作 5x5 的按钮网格。 I use buttons because I dont know what else to use.
我使用按钮是因为我不知道还能使用什么。 but on this grid I need to add X and 0 depending on where they are on the quixo board.
但在这个网格上,我需要根据它们在 quixo 板上的位置添加 X 和 0。
essentially I have a matrix本质上我有一个矩阵
as an example举个例子
[[-,-,-,-,X]
[-,-,-,-,X]
[-,-,-,0,-]
[0,-,-,0,X]
[0,-,0,0,-]]
how can I place this on that grid of buttons?我怎样才能把它放在那个按钮网格上? the buttons don't need to be clicked.
不需要点击按钮。 the are just there to show info
只是在那里显示信息
This is how I would do it, might not be the most elegant solution:这就是我的做法,可能不是最优雅的解决方案:
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()
Let me know if this helps:)让我知道这是否有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.