Tkinter嵌套框架使用类

huangapple go评论67阅读模式
英文:

Tkinter Nested Frame using Classes

问题

我正在尝试构建一个带有主窗口的GUI,其中包含一个包含标头标签的嵌套框架(使用不同类创建)。

在下面的代码片段中,我期望由FrameHeader类创建的框架位于MainWindow.container框架内(在MainWindow.container属性的初始化期间,container属性被传递为父级)。

然而,当运行下面的代码时,FrameHeader框架位于容器框架之后,而不是位于容器框架内。

我对tkinter不太熟悉,有人可以帮助我理解,在不同类之间切换时我漏掉了什么吗?

英文:

I am trying to build a GUI with the main Frame having nested frame containing header label (created with different class).

In below snippet, I am expecting frame created by FrameHeader class to be inside MainWindow.container Frame (while initialization of MainWindow.container attribute, container attribute is passed as parent).

Still, when the below code is run, FrameHeader frame is at the bottom after container frame, instead of being inside the container frame.

I am new to tkinter, can someone help me out here, what am I missing while going between different classes?

from tkinter import *

class FrameHeader(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, bg='red',relief=RAISED, borderwidth=2)
        self.pack(fill=BOTH, side=TOP)
        lblTitle = Label(self, text='Welcome to the Program!')
        lblTitle.pack(fill=BOTH)

class MainWindow(Tk):
    def __init__(self,*args):
        Tk.__init__(self,*args)
        self.geometry('400x300')

        # Main Container
        container=Frame(self, bg='black')
        container.pack(side=TOP, expand=TRUE, fill=BOTH)

        frameHeader=FrameHeader(container, self)

if __name__=='__main__':
    mainWindow=MainWindow()
    mainWindow.mainloop()

答案1

得分: 2

你没有将parent传递给Frame.__init,所以FrameHeader的父级默认为根窗口而不是容器。

代码需要是这样的:

Frame.__init__(self, parent, bg='red', relief=RAISED, borderwidth=2)
英文:

You are neglecting to pass parent to Frame.__init, so the parent of FrameHeader defaults to the root window rather than the container.

The code needs to be this:

Frame.__init__(self, parent, bg='red',relief=RAISED, borderwidth=2)

huangapple
  • 本文由 发表于 2020年1月3日 22:20:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定