【问题标题】:Making a grid of Entry boxes in Tkinter in a loop在循环中在 Tkinter 中制作一个输入框网格
【发布时间】:2013-04-05 19:18:06
【问题描述】:

我想制作一个输入框网格,我可以对其进行编辑并保存到其他地方的文本文件中,但是每次我运行我的代码时,如果我调用变量“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()

【问题讨论】:

    标签: python loops widget grid tkinter


    【解决方案1】:

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

        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]
    

    你可以随意修改它。

    【讨论】:

    • 感谢@mgilson,它成功了,现在我可以继续遇到另一个错误!
    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 2023-02-04
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多