Tkinter中从grid切换为place布局后按钮不显示问题
解决Tkinter中place布局按钮不显示的问题
问题原因
你的Frame使用默认的pack()方法时,Frame的尺寸会自适应内部控件大小,但place布局的控件不会触发父容器(Frame)自动调整尺寸,导致Frame的宽高为0,按钮虽然存在,但随父容器一起被隐藏。而grid布局会让Frame根据控件尺寸自动调整,所以之前能正常显示。
修复方案
有两种简单的解决办法:
方案1:让Frame填充整个窗口
修改Frame的pack参数,让它铺满主窗口:
def __init__(self): self.root = tk.Tk() self.frame = tk.Frame(self.root) # 添加fill和expand参数,让Frame填充整个窗口 self.frame.pack(fill=tk.BOTH, expand=True) practiceButton = tk.Button(self.frame, text=f"Practice Terms", font=('Louis George Cafe', 20), command=lambda: self.showFrame('review')) practiceButton.place(relx=0.5, rely=0.5, anchor=tk.CENTER) # 加anchor让按钮自身中心对准定位点,避免偏移 self.root.geometry("750x750") self.root.mainloop()
方案2:给Frame设置固定尺寸
如果不需要Frame铺满窗口,可直接指定Frame的宽高:
def __init__(self): self.root = tk.Tk() self.frame = tk.Frame(self.root, width=750, height=750) # 设置固定尺寸 self.frame.pack() practiceButton = tk.Button(self.frame, text=f"Practice Terms", font=('Louis George Cafe', 20), command=lambda: self.showFrame('review')) practiceButton.place(relx=0.5, rely=0.5, anchor=tk.CENTER) self.root.geometry("750x750") self.root.mainloop()
内容的提问来源于stack exchange,提问作者Naboo01
相关产品推荐
相关产品推荐

