You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter中是否可以将frame框架居中显示在屏幕中央

实现方案

这个需求完全可以实现,首先先理清你的代码架构逻辑:你当前采用的是单主窗口+多Frame堆叠切换的设计,所有Frame都嵌套在同一个主窗口内部,不存在独立的Frame窗口,你说的「Frame弹出时居中」本质是让承载Frame的主窗口在页面切换(或启动)时居中显示。

具体修改步骤

你只需要在你的SampleApp主类中新增窗口居中逻辑,每次切换页面时调用即可,修改点如下:

  1. 新增center_window方法,用于计算并设置主窗口的居中坐标
  2. 修改show_frame方法,切换页面完成后自动调用居中方法
  3. 删除StartPage中无效的「Go to Page Two」按钮,你的原代码中没有定义PageTwo类,点击会触发报错

修改后的完整代码

import tkinter as tk                
from tkinter import font as tkfont

LARGE_FONT = ("Verdana", 12)


class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        container = tk.Frame(self)
        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
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def center_window(self):
        # 先刷新窗口状态,确保获取到实际的窗口尺寸
        self.update_idletasks()
        # 获取屏幕分辨率
        screen_w = self.winfo_screenwidth()
        screen_h = self.winfo_screenheight()
        # 获取当前窗口实际宽高
        window_w = self.winfo_width()
        window_h = self.winfo_height()
        # 计算居中坐标
        x = (screen_w - window_w) // 2
        y = (screen_h - window_h) // 2
        # 应用窗口位置设置
        self.geometry(f"{window_w}x{window_h}+{x}+{y}")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()
        # 切换页面后自动居中
        self.center_window()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button1.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

补充说明

如果你后续需要实现点击按钮弹出独立的新窗口(而非在当前窗口内切换页面),可以使用tk.Toplevel控件创建子窗口,子窗口的居中逻辑和上述center_window方法完全一致,只需要把方法中的self替换为对应的Toplevel实例即可。

内容的提问来源于stack exchange,提问作者ChrisBoss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:27:03