Python和Tkinter - 写入由按钮网格制成的文件矩阵

时间:2017-05-17 17:57:22

标签: python python-3.x file tkinter grid

这是我第一次用Python编码,我有一个带5 x 5按钮的Tkinter网格:

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.close()
    myFile = open("example.txt",'r')
    print(myFile.read())

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

我正在尝试根据网格中按钮的颜色在.txt文件中写一个矩阵(0表示灰色,1表示红色,列之间有空格,每行表示新行)但是我得到了这个错误,我不知道为什么:

File "C:\Users\Dana\Desktop\PyPlay\ExampleTkinter.py", line 47, in <module>
app = App(root)
 File "C:\Users\Dana\Desktop\PyPlay\ExampleTkinter.py", line 12, in __init__
    buttonS = Button(self.BottomFrame, text="Save", command=self.saveToFile())
  File "C:\Users\Dana\Desktop\PyPlay\ExampleTkinter.py", line 33, in saveToFile
    myFile=open("example.txt", 'w')
PermissionError: [Errno 13] Permission denied: 'example.txt'

我尝试更改文件名,添加完整路径C:\Users\Dana\Desktop\PyPlay\example.txt但结果相同。

1 个答案:

答案 0 :(得分:0)

两件事:

1

command=self.saveToFile()

应改为:

command=self.saveToFile

否则命令将等于函数的返回值,即无。

2

要么在其他地方打开example.txt文件,要么忘记关闭它。或者您没有创建文件的权限,或者该文件具有阻止用户更改文件的权限设置。尝试以管理员身份运行。