Tkinter扩展按钮组件填充框架并随窗口缩放问题求助
解决Tkinter按钮随窗口自动缩放的问题
嘿,我懂你遇到的困扰啦!你的按钮没法跟着窗口一起缩放,核心问题出在承载按钮的leftFrame没有配置填充和扩展属性——哪怕按钮本身加了expand=True和fill='both',但框架自己没跟着窗口变大,按钮自然没地方伸展~
只需要给leftFrame的pack()方法加上两个关键参数就能搞定,看我修改后的完整代码:
from tkinter import * root = Tk() leftFrame = Frame(root) # 新增fill=BOTH和expand=True,让框架填满左侧区域并随窗口扩展 leftFrame.pack(side=LEFT, fill=BOTH, expand=True) rightFrame = Frame(root) rightFrame.pack(side=RIGHT) button1 = Button(leftFrame, text="Round 1", fg="white", bg="black") button2 = Button(leftFrame, text="Round 2", fg="yellow", bg="blue") button3 = Button(leftFrame, text="Round 3", fg="purple", bg="cyan") button4 = Button(leftFrame, text="Round 4", fg="green", bg="orange") button1.pack(expand=True, fill='both') button2.pack(expand=True, fill='both') button3.pack(expand=True, fill='both') button4.pack(expand=True, fill='both') root.mainloop()
给你拆解下这两个参数的作用:
fill=BOTH:让leftFrame在水平和垂直两个方向上,完全填充父容器(也就是root窗口)的可用空间expand=True:告诉Tkinter,当窗口大小调整时,把额外的空间分配给leftFrame
这样修改后,窗口扩展时leftFrame会先跟着放大,里面的四个按钮因为已经设置了expand=True和fill='both',就会自动填满框架的空间,实现随窗口缩放的效果啦!
内容的提问来源于stack exchange,提问作者Noobie




