Tkinter中pack方法的anchor选项失效问题求助
解决Tkinter中Anchor选项不生效的问题
问题出在main.py里对PageOne的布局设置上——当前PageOne的Frame并未填满父容器空间,导致内部标签无法贴到屏幕两侧。
修改方案
把main.py中self.page_one.pack(expand='True')这一行,修改为:
self.page_one.pack(expand=True, fill="both")
修改后的完整代码
main.py
import tkinter as tk from page_one import PageOne class Main(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.page_one = PageOne(self) # 新增fill="both"让PageOne填满父容器 self.page_one.pack(expand=True, fill="both") if __name__ == "__main__": root = tk.Tk() main = Main(root) root.attributes("-fullscreen", True) main.pack(side="top", fill="both", expand=True) root.mainloop()
page_one.py(无需修改)
import tkinter as tk class PageOne(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.one_label = tk.Label(self, text='LEFT') self.one_label.pack(padx=(20,0), side='left', anchor='w') self.two_label = tk.Label(self, text='RIGHT') self.two_label.pack(padx=(0,20), side='right', anchor='e') if __name__ == "__main__": root = tk.Tk() PageOne(root).pack(side="top", fill="both", expand=True) root.mainloop()
原理说明
expand=True仅让组件在父容器有剩余空间时具备扩展能力,而fill="both"才会让组件横向、纵向都填满父容器。修改后PageOne会占满整个Main容器,此时内部标签的side='left'和side='right'就能让标签分别贴到容器的左右边缘,anchor参数的效果也会正常体现。
内容的提问来源于stack exchange,提问作者Kome Gognome
相关产品推荐
相关产品推荐

