如何将列表元素按顺序放入标签矩阵中?

时间:2018-04-27 01:48:49

标签: python-3.x for-loop matrix tkinter label

我正在为这个for循环而苦苦挣扎。如何从位置[1],[1]开始按顺序将数字分别放在矩阵中?当它到达行的末尾时,它将从第1列开始将序列继续到下一行。

我拥有的代码是列形式或行形式。

我知道我错过了什么,但不知道是什么。非常感谢。

import tkinter as tk
the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = {}

def main():

    root = tk.Tk()
    root.title("class basic window")
    root.geometry("800x500")
    root.config(background="LightBlue4")
    app = Application(root)
    root.mainloop()


class Application(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent, bg="ivory2", bd=2, relief=tk.RAISED)   
        self.parent = parent
        self.pack(fill=tk.BOTH, expand=1)
        self.initUI()


    def initUI(self):

        for i in range(8):
            for j in range(6):
                self.label=tk.Label(self, relief="ridge",width=13, height=3 )
                self.label.grid(row=i, column=j, sticky="nsew", )


        i = 0
        for num in the_list:
            new_list[i,j] = tk.IntVar()
            new_list[i,j].set(num)
            self.label = tk.Label(self, textvariable=new_list[i,j])
            self.label.grid(row=i, column=j)
            i += 1




if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

不确定这是否是你想要完成的事情,但听起来你想要将the_list中的数字放入连续的框中,从左上角开始,从左到右工作,然后从上到下。如果是这种情况,以下代码将执行此操作。

import tkinter as tk

the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = {}

def main():

    root = tk.Tk()
    root.title("class basic window")
    root.geometry("800x500")
    root.config(background="LightBlue4")
    app = Application(root)
    root.mainloop()

class Application(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent, bg="ivory2", bd=2, relief=tk.RAISED)   
        self.parent = parent
        self.pack(fill=tk.BOTH, expand=1)
        self.initUI()


    def initUI(self):

        i = 0
        for r in range(8):
            for c in range(6):
                self.label=tk.Label(self, relief="ridge",width=13, height=3 )
                self.label.grid(row=r, column=c, sticky="nsew", )
                if i < len(the_list):
                    self.label['text'] = str(the_list[i])
                    i += 1

if __name__ == '__main__':
    main()