gpt4 book ai didi

Python TkInter 网格问题

转载 作者:行者123 更新时间:2023-11-28 22:26:45 24 4
gpt4 key购买 nike

我在 TkInter 中有一个网格:

from tkinter import *

class App():
def __init__(self, root):
self.root = root
self.TopFrame = Frame(root)
self.MiddleFrame = Frame(root)
self.BottomFrame = Frame(root)
self.TopFrame.grid(row=0)
self.MiddleFrame.grid(row=5)
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)
row2 = []
for k in range(4):
row2.append(Button(self.MiddleFrame,width=6,height=3,command=lambda i=5, k=k: self.getClick(i, k),background='gray'))
row2[-1].grid(row=6,column=k, pady=10)

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")
for column in range(4):
bg_color2 = self.grid[5][column].cget('bg')
if bg_color2 == "red":
myFile.write("1 ")
else:
myFile.write("0 ")
myFile.write("\n")
myFile.close()
myFile = open("example.txt",'r')
print(myFile.read())
myFile.close()

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

但问题是来自中间网格的按钮在点击时不会改变它们的颜色并返回此错误:

line 1699, in __call__
return self.func(*args)
line 28, in <lambda>
row2.append(Button(self.MiddleFrame,width=6,height=3,command=lambda i=5, k=k: self.getClick(i, k),background='gray'))
line 32, in getClick
orig_color = self.grid[i][j].cget('bg')
IndexError: list index out of range

还有当我按下 Save 按钮时:

  line 1699, in __call__
return self.func(*args)
line 39, in saveToFile
myFile=open("example.txt", 'w')
PermissionError: [Errno 13] Permission denied: 'example.txt'

我做错了什么?

最佳答案

对于第一个错误,我认为你需要添加:

self.grid.append(row2)

在 Function 函数末尾的第 55 行第 11 列中,因为这会将其添加到您的 self.grid 对象并允许在 self.getClick 中访问按钮。

第二个错误通常发生在您自己打开文本文件时。尝试关闭它,看看是否有帮助

关于Python TkInter 网格问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44551709/

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