Tkinter中Treeview未嵌入指定Frame,占满全屏问题求助
解决Tkinter Treeview未适配指定Frame而是占满屏幕的问题
问题根源
你的代码里存在一个Tkinter布局的典型错误:
owner_data_Frame = Frame(self.root, bd=2, relief = "solid").place(x=34, y=600, width = 1032, height = 189)
place()方法的返回值是None,这意味着owner_data_Frame实际是None。当Treeview的父组件被设为None时,Tkinter会默认将其挂载到根窗口root上,最终导致Treeview占满整个屏幕。
修正方案
拆分Frame的创建与布局步骤,先实例化Frame对象,再单独调用place()方法完成布局:
class employeeClass: def __init__(self,root): self.root = root self.root.geometry("1098x822+342+83") self.root.title("Owner") self.root.config(bg = "white") self.root.focus_force() # 先创建Frame对象,再执行布局 owner_data_Frame = Frame(self.root, bd=2, relief = "solid") owner_data_Frame.place(x=34, y=600, width = 1032, height = 189) # 此时Treeview的父组件为正确的Frame实例 self.OwnerTable = ttk.Treeview(owner_data_Frame, columns = ("owner_id", "name", "phone_no", "aadhaar_no", "address", "city", "state", "pincode")) self.OwnerTable.heading("owner_id", text = "Owner ID") self.OwnerTable.heading("name", text = "Name") self.OwnerTable.heading("phone_no", text = "Phone No.") self.OwnerTable.heading("aadhaar_no", text = "Aadhaar No.") self.OwnerTable.heading("address", text = "Address") self.OwnerTable.heading("city", text = "City") self.OwnerTable.heading("state", text = "State") self.OwnerTable.heading("pincode", text = "Pincode") self.OwnerTable["show"] = "headings" self.OwnerTable.pack(fill=BOTH, expand=1) if __name__ == "__main__": from tkinter import Tk, Frame, ttk # 补充必要导入,避免运行报错 root = Tk() obj = employeeClass(root) root.mainloop()
额外提示
- 可以给Frame添加背景色(如
bg="lightgray"),方便直观确认Frame的位置和尺寸是否符合预期 - 同一父组件内不要混用
pack()、place()、grid()三种布局方法,本次代码中Frame用place、Treeview在Frame内用pack的组合是合理的
内容的提问来源于stack exchange,提问作者Manya Garg
相关产品推荐
相关产品推荐

