gpt4 book ai didi

python - Tkinter 16 个网格(4x4 方向),每个网格有 5x5 按钮网格

转载 作者:行者123 更新时间:2023-12-01 02:57:06 24 4
gpt4 key购买 nike

我有这个简单的 5x5 按钮网格:

from tkinter import *

class App():
def __init__(self, root):
self.root = root
self.TopFrame = Frame(root)
self.BottomFrame = Frame(root)
self.TopFrame.grid(row=0)
self.BottomFrame.grid(row=6)

buttonQ = Button(self.BottomFrame, text="Quit", command=quit)
buttonS = Button(self.BottomFrame, text="Save", command=self.saveToFile)
buttonS.grid(row=0, column=0, padx=10)
buttonQ.grid(row=0, column=1, padx=10)

def Function(self):
self.grid = []
for i in range(5):
row = []
for j in range(5):
row.append(Button(self.TopFrame,width=6,height=3,command=lambda i=i, j=j: self.getClick(i, j),background='gray'))
row[-1].grid(row=i,column=j)
self.grid.append(row)

def getClick(self, i, j):
orig_color = self.grid[i][j].cget('bg')
if orig_color=="red":
self.grid[i][j]["bg"]="gray"
else:
self.grid[i][j]["bg"]="red"

def saveToFile(self):
myFile=open("example.txt", 'w')
for line in range(5):
for column in range(5):
bg_color = self.grid[line][column].cget('bg')
if bg_color == "red":
myFile.write("1 ")
else:
myFile.write("0 ")
myFile.write("\n")
#myFile.flush()
myFile.close()
myFile = open("example.txt",'r')
print(myFile.read())
myFile.close()

root = Tk()
app = App(root)
app.Function()
root.mainloop()

我想将其乘以 16 次(排列在 4 行 4 列的矩阵中 - 一个单元格具有 5x5 按钮矩阵),它们之间有空格,并且下面是“退出”和“保存”按钮。我只能通过使用框架来实现吗?有没有办法将5x5的按钮网格乘以16倍并排列成4x4的矩阵?

我是 Python 编程新手,所以请保持温柔:)

最佳答案

遵循abstraction principle在编程中,您可以将 5×5 按钮单元定义为一个类(在 App 类之外),如下所示:

class Cell5by5():
def __init__(self, parent):
self.frame = Frame(parent)
self.buttons = []
for i in range(5):
row = []
for j in range(5):
row.append(Button(self.frame,width=6,height=3,
command=lambda i=i, j=j: self.getClick(i, j),
background='gray'))
row[-1].grid(row=i,column=j)
self.buttons.append(row)

def getClick(self, i, j):
orig_color = self.buttons[i][j].cget('bg')
if orig_color=="red":
self.buttons[i][j]["bg"]="gray"
else:
self.buttons[i][j]["bg"]="red"

然后在您的 App 类中,您可以根据需要创建任意数量的 Cell5by5 实例:

class App():
def __init__(self, root):
self.root = root
...
self.create_cells()

def create_cells(self):
self.cells = []
for i in range(4):
row = []
for j in range(4):
row.append(Cell5by5(self.root))
row[-1].frame.grid(row=i, column=j, padx=2, pady=2)
self.cells.append(row)

def saveToFile(self):
# Each button is now obtainable by calling:
# self.cells[line][column].buttons[subline][subcolumn]

root = Tk()
app = App(root)
root.mainloop()

另外,我将按钮网格重命名为 self.buttons 以防止与 tkinter 的 .grid() 方法混淆

关于python - Tkinter 16 个网格(4x4 方向),每个网格有 5x5 按钮网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44112369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com