在Tkinter中创建一个Entry框网格

时间:2013-04-05 19:18:07

标签: python loops widget grid tkinter

我想创建一个可以编辑的输入框网格并保存到其他地方的文本文件中,但每次运行我的代码时,如果我调用变量“e”,我只能编辑最后一个框是的。

from Tkinter import *

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.TXTlist = open('txtlist.txt', 'r+')
        self.row = self.TXTlist.readline()
        self.row = self.row.rstrip('\n')
        self.row = self.row.replace('characters = ', "") #should end up being "6"
        self.columns = self.TXTlist.readline()
        self.columns = self.columns.rstrip('\n')
        self.columns = self.columns.replace('columns = ', "") #should end up being "9"
        i = 0
        x = 0
        for i in range (int(self.row)):
            for x in range (int(self.columns)):
                sroot = str('row' + str(i) + 'column' + str(x))
                e = Entry(self, width=15)
                e.grid(row = i, column = x, padx = 5, pady = 5, sticky = W)
                e.delete(0, END)
                e.insert(0, (sroot))
                x = x + 1
            x = 0
            i = i + 1
root = Tk()
root.title("Longevity")
root.geometry("450x250")
app = Application(root)
root.mainloop()

1 个答案:

答案 0 :(得分:0)

我会将条目存储在某种数据结构中,以便以后轻松访问它们。列表列表可以很好地用于此:

    self.entries = []
    for i in range (int(self.row)):
        self.entries.append([])
        for x in range (int(self.columns)):
            ...
            e = Entry(self, width=15)
            self.entries[-1].append(e)
            ...

现在您可以参考输入框:

 self.entries[row_idx][col_idx]

你可以根据需要修改它。