尝试使用Tkinter中的类来创建多个帧

时间:2015-01-06 19:36:45

标签: python class user-interface tkinter

我试图在我的主要父窗口小部件中创建2个框架 - 一个使用grid()方法,另一个使用pack()方法。我首先以程序方式编写它并且它太乱了,所以我试图使用类来清理代码。下面是相关代码,我尝试使用 init 方法创建2个帧,但它会引发各种错误。

from tkinter import *

class Application(Frame):
    """This class creates packed frames for the GUI"""
    def __init__(self, master):
        Frame.__init__(self, master)
        self.framepack = Frame(master)
        self.framepack.pack(side=BOTTOM, fill=X)
        self.framegrid = Frame(master)
        self.framegrid.pack(side=TOP)
        self.create_widgets()

    def create_widgets(self):
        #Container 1 using LabelFrame, houses email and password labels and entries
        self.inputlabels1 = LabelFrame(self, self.framepack, text="Input email login information here")
        self.inputlabels1.grid(row=0, column=0, padx=10, pady=10)
        self.emailfield = Label(self.inputlabels1, text="Email Address")     #Labels
        self.passfield = Label(self.inputlabels1, text="Password")

root = Tk()
app = Application(root)
root.mainloop()

整个事情都崩溃了。问题代码是:

        self.inputlabels1 = LabelFrame(self, self.framepack, text="Input email login information here")

我试图将这个Labelframe小部件放入我之前初始化的两个框架中的一个框架中,但它会引发我的错误。我的语法有问题吗?

2 个答案:

答案 0 :(得分:2)

我修改了你的例子,以便它可以工作,并显示一些东西。在目前的形式,它不起作用。另外,我在框架中添加了颜色,因此很容易看到它们。这有助于组织您的布局,并了解正在发生的事情:

from tkinter import *

class Application(Frame):
    """This class creates packed frames for the GUI"""
    def __init__(self, master):
        Frame.__init__(self, master)

        # added width=180, height=40, background='red'
        self.framepack = Frame(master, width=180, height=40, background='red')
        self.framepack.pack(side=BOTTOM, fill=X)

        # added width=180, height=40, background='green'
        self.framegrid = Frame(master, width=180, height=40, background='green')
        self.framegrid.pack(side=TOP)
        self.create_widgets()

    def create_widgets(self):
        # Container 1 using LabelFrame, houses email and password labels and entries

        # Removed `self,` from the orginal code.
        self.inputlabels1 = LabelFrame(self.framepack, text="Input email login information here")
        self.inputlabels1.grid(row=0, column=0, padx=10, pady=10)        
        self.emailfield = Label(self.inputlabels1, text="Email Address")     #Labels

        # Called pack()
        self.emailfield.pack()
        self.passfield  = Label(self.inputlabels1, text="Password")

        # Called pack()
        self.passfield.pack()

root = Tk()
app = Application(root)
root.mainloop()

enter image description here

希望这有帮助。

答案 1 :(得分:1)

你想给你的LabelFrame两个父母。父母应为self.framepack。删除第一个参数应解决问题:

self.inputlabels1 = LabelFrame(self.framepack, text="Input email login information here")