tkinter使用sticky='nsew'时frame无法完全拉伸该如何解决
问题核心原因
你给根窗口的第0行(放置顶部按钮的行)设置了weight=1,导致窗口纵向拉伸时,第0行和第1行(放置frame的行)会按权重比例分配额外空间,按钮所在行被拉高,挤占了下方frame的填充空间,所以frame没法铺满剩余区域。
修复步骤
- 删除代码中
Grid.rowconfigure(root,0,weight=1)这行配置,按钮所在的第0行不需要拉伸权重,保持固定高度即可 - 保留
Grid.rowconfigure(root,1,weight=1)配置,让所有纵向额外空间都分配给放置frame的第1行 - 其余网格配置、控件布局无需调整,即可保留顶部按钮的同时让frame铺满第二行跨两列的全部区域
修改后可正常运行的完整代码
from tkinter import * root=Tk() root.title("manage your cashflow") #for setting full screen window screen_width=root.winfo_screenwidth() screen_height=root.winfo_screenheight() print(screen_height, screen_width) root.geometry("%dx%d" % (screen_width,screen_height)) root.configure(bg='grey') #configure # 已移除原第0行的weight配置 Grid.columnconfigure(root,0,weight=1) Grid.columnconfigure(root,1,weight=1) # creating tabs up_button1= Button(root, text="the list of month", bg='#ebca87') up_button1.grid(row=0,column=0, sticky='NEW') up_button2=Button(root, text="the new month",bg='#ebca87') up_button2.grid(row=0,column=1,sticky='NEW',pady=0) #class for frames class frame: #method for def frame2(self): #for frame sticky Grid.rowconfigure(root,1,weight=1) Grid.columnconfigure(root,0,weight=1) Grid.columnconfigure(root,1,weight=1) #frame for listbox,加了白色背景方便验证填充效果,不需要可删除 frame2=Frame(root, bg='white') frame2.grid(row=1,column=0,columnspan=2,sticky="NSEW") Grid.rowconfigure(frame2,0,weight=1) Grid.columnconfigure(frame2,0,weight=1) Grid.columnconfigure(frame2,1,weight=1) salary_text=Label(frame2,text="salary") salary_text.pack() salary_entry=Entry(frame2) salary_entry.pack() frame_ob=frame() frame_ob.frame2() root.mainloop()
内容的提问来源于stack exchange,提问作者dead day
相关产品推荐
相关产品推荐

