如何通过For循环在python中创建多个框架?

时间:2013-07-27 21:29:16

标签: python

我正在使用Tkinter进行python的GUI编程 我使用下面的代码在我的Tkinter根窗口中创建了4个帧(Frame1,Frame2,Frame3和Frame4):

import tkinter as tki

class App(object):

    def __init__(self):
        self.root = tki.Tk()        
        self.root.wm_title("Play With python")
        for r in range(8):
            self.root.rowconfigure(r, weight=1)
        for c in range(2):
            self.root.columnconfigure(c, weight=1)
    # Create Frames
        Frame1 = tki.Frame(self.root, borderwidth=1, bg = 'blue')
        Frame1.grid(row = 0, column = 0, rowspan = 2, columnspan = 2, sticky = 'w, e, n, s')

        Frame2 = tki.Frame(self.root, borderwidth=1, bg = 'blue')
        Frame2.grid(row = 2, column = 0, rowspan = 2, columnspan = 2, sticky = 'w, e, n, s')

        Frame3 = tki.Frame(self.root, borderwidth=1, bg = 'blue')
        Frame3.grid(row = 4, column = 0, rowspan = 2, columnspan = 2, sticky = 'w, e, n, s')

        Frame4 = tki.Frame(self.root, borderwidth=1, bg = 'blue')
        Frame4.grid(row = 6, column = 0, rowspan = 2, columnspan = 2, sticky = 'w, e, n, s')

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

我想用 for循环做同样的事情,使我的代码可读,就像在我的真实代码中一样,帧数大约是12。

我正在尝试使用以下代码输出相同的内容:

import tkinter as tki

class App(object):

    def __init__(self):
        self.root = tki.Tk()        
        self.root.wm_title("Play With python")
        for r in range(8):
            self.root.rowconfigure(r, weight=1)
        for c in range(2):
            self.root.columnconfigure(c, weight=1)
    # Create Frames
        j = 0
        for i in range(1,5):
            Framei = tki.Frame(self.root, borderwidth=1, bg = 'blue')
            Framei.grid(row = j, column = 0, rowspan = 2, columnspan = 2, sticky = 'w, e, n, s') 
            j = j + 2
app = App()
app.root.mainloop()

问题:

正如我可以看到的问题,此代码创建了4个帧,但名称引用与 Framei 相同(而不是Frame1,Frame2,Frame3和Frame4)。 但我想要4个不同名称的帧(Frame1,Frame2,Frame3和Frame4)。

我知道我的问题与在运行时创建变量非常相关,但是当我第一次应用它时面临问题。

我使用的Python版本是3.0.1 请帮忙......

1 个答案:

答案 0 :(得分:3)

您应该将Frame个实例放在一个列表中,如下所示:

import tkinter as tki

class App(object):

    def __init__(self):
        self.root = tki.Tk()
        self.root.wm_title("Play With python")
        for r in range(8):
            self.root.rowconfigure(r, weight=1)
        for c in range(2):
            self.root.columnconfigure(c, weight=1)

        # Create a list of the Frames in the order they were created
        frames = []
        j = 0
        for i in range(1,5):
            Frame = tki.Frame(self.root, borderwidth=1, bg = 'blue')
            Frame.grid(row = j, column = 0, rowspan = 2, columnspan = 2, sticky = 'w, e, n, s')

            # Add the Frame to the list
            frames.append(Frame)

            # Also, just as an FYI, j = j + 2 can be better written like this
            j += 2

        # To demonstrate
        print(frames)

        # This is the first Frame created
        print(frames[0])

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

要访问框架,只需将列表编入索引。