Tkinter继承Frame类后初始化的Label无法在GUI中显示的问题
问题原因与解决方法
你的代码问题出在继承自tk.Frame的Window实例没有被添加到主窗口的布局管理器中:
- 当你把Label的父组件设为
self(也就是Window这个Frame)时,Label是Frame的子组件,但Frame本身没有通过pack()/grid()/place()方法被布局到主窗口,所以整个Frame都处于隐藏状态,里面的Label自然也显示不出来。 - 而把Label父组件改成
parent(主窗口root)时,Label直接属于主窗口,grid()方法会让主窗口自动调整大小来显示它,所以能看到内容。
两种解决方式
方式一:在创建实例后为Frame添加布局
修改主函数部分,给app(也就是你的Frame实例)调用布局方法:
if __name__ == "__main__": root = tk.Tk() app = Window(root) app.pack(fill="both", expand=True) # 让Frame填充整个主窗口 root.mainloop()
方式二:在Frame的初始化方法内为自己添加布局
在Window类的__init__末尾添加布局代码,这样创建实例时会自动完成布局:
def __init__(self, parent = None): tk.Frame.__init__(self, parent) self.parent = parent self.yearLabel = tk.Label(self, text="Label",width=5) self.yearLabel.grid(row=0,column=1) self.pack(fill="both", expand=True) # 内部完成布局
修改后的完整代码示例(方式一)
import tkinter as tk class Window(tk.Frame): def __init__(self, parent = None): tk.Frame.__init__(self, parent) self.parent = parent self.yearLabel = tk.Label(self, text="Label",width=5) self.yearLabel.grid(row=0,column=1) if __name__ == "__main__": root = tk.Tk() app = Window(root) app.pack(fill="both", expand=True) root.mainloop()
其他示例中能用self作为父组件显示内容,都是因为它们都对Frame本身做了布局处理,只是你可能没留意到这一步。
内容的提问来源于stack exchange,提问作者Tim Williams
相关产品推荐
相关产品推荐

