tkinter控件无法放置在Frame内,参照多Frame切换模板开发无效求助
问题修复方案
根因定位
- 你在循环创建
StartPage、PageOne两个页面对象时,注释了将页面对象布局到父容器container的frame.grid(row=0, column=0, sticky="nsew")语句,所有页面Frame从始至终都没有被渲染到窗口中,所以页面内的控件自然无法显示。 - 父容器
container的pack配置中expand=False会导致容器无法填充满整个窗口,即使页面布局成功也会出现显示截断问题。
修改代码
只需调整两处代码即可正常运行:
- 取消
frame.grid语句的注释 - 将
container.pack的expand参数改为True
修改后的完整可运行代码如下:
import tkinter as tk from tkinter import * class App(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(self) # 这里将expand改为True让容器占满窗口 container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame # put all of the pages in the same location; # the one on the top of the stacking order # will be the one that is visible. # 取消这行的注释,将页面布局到容器中 frame.grid(row=0, column=0, sticky="nsew") self.show_frame("StartPage") def show_frame(self, page_name): '''Show a frame for the given page name''' frame = self.frames[page_name] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller def check_user_login(): #code removed return None #create a canvas to place images on canvas = tk.Canvas(self, bg = "#5c5c5c",height = 400,width = 800,bd = 0,highlightthickness = 0,relief = "flat") canvas.place(x = 0, y = 0) #login button button = tk.Button(self, text="Go to the start page",command=lambda: controller.show_frame("PageOne")) button.place(x = 356, y = 290,width = 89,height = 29) class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller #create a canvas to place images on canvas = Canvas(self,bg = "#5c5c5c",height = 400,width = 800,bd = 0,highlightthickness = 0,relief = "flat") canvas.place(x = 0, y = 0) button = tk.Button(self, text="Go to the start page", command=lambda: controller.show_frame("StartPage")) button.pack() if __name__ == "__main__": app = App() app.geometry("800x400") # app.configure(bg = "#5c5c5c") app.resizable(False, False) app.mainloop()
修改后运行即可正常在两个页面之间切换,所有控件都可以正常显示。
内容的提问来源于stack exchange,提问作者Will Jordan
相关产品推荐
相关产品推荐

