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

Custom Tkinter启动屏无法精准居中问题求助

Custom Tkinter启动屏精准居中解决方案

你的代码核心问题在于未先初始化窗口布局就直接设置几何参数,加上overrideredirect(True)移除了系统窗口边框,导致尺寸计算和实际窗口渲染出现偏差。以下是修正方案:

修正步骤

  1. 在计算居中坐标前,调用update_idletasks()让窗口完成所有布局更新,确保组件尺寸完全生效
  2. 改用浮点除法计算坐标,避免整数除法的精度丢失问题

修正后的完整代码

import customtkinter as CTK
from PIL import Image

splash_screen = CTK.CTk()
splash_screen.overrideredirect(True)

screen_width = splash_screen.winfo_screenwidth()
screen_height = splash_screen.winfo_screenheight()

splash_width = int(0.29 * screen_width)
splash_height = int(0.31 * screen_height)

splash_image = CTK.CTkImage(light_image=Image.open('splash_image.jpg'), size=(splash_width, splash_height))
splash_image_label = CTK.CTkLabel(splash_screen, image=splash_image, text='')
splash_image_label.pack(fill=CTK.BOTH, expand=True)

# 关键:触发窗口布局更新,确保尺寸计算准确
splash_screen.update_idletasks()

# 精准计算居中坐标
x = int(screen_width / 2 - splash_width / 2)
y = int(screen_height / 2 - splash_height / 2)

splash_screen.geometry(f"{splash_width}x{splash_height}+{x}+{y}")
splash_screen.mainloop()

原理说明

  • update_idletasks():强制窗口处理所有待执行的布局、渲染任务,保证你设置的组件尺寸能被系统正确识别
  • 浮点除法转整数:避免//操作截断小数部分导致的坐标偏移,让窗口位置计算更精准
  • overrideredirect(True)移除了系统边框,此时窗口的几何尺寸就是你设置的内容尺寸,无需额外调整边框偏移

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:02:34