tkinter实现splash启动图屏幕居中显示时如何消除周边黑边
问题原因
你当前的代码将窗口、画布尺寸都设置为屏幕大小的80%,而你使用的splash原图尺寸仅为400x400,远小于窗口尺寸,露出了你设置的黑色画布背景,就会出现四周黑边的效果。
解决方案
直接将窗口和画布的尺寸设置为和图片实际大小一致,再计算居中坐标显示即可,修改后的可运行代码如下:
import tkinter as tk root = tk.Tk() root.overrideredirect(True) # 获取屏幕分辨率 screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() # 加载启动图并读取图片实际尺寸 image_file = "test.gif" image = tk.PhotoImage(file=image_file) img_width = image.width() img_height = image.height() # 计算窗口居中的坐标值 x = (screen_width - img_width) // 2 y = (screen_height - img_height) // 2 # 设定窗口尺寸等于图片尺寸,且居中显示 root.geometry(f"{img_width}x{img_height}+{x}+{y}") # 画布尺寸和图片保持一致,去掉默认边框避免多余边缘 canvas = tk.Canvas(root, height=img_height, width=img_width, highlightthickness=0) canvas.create_image(img_width/2, img_height/2, image=image) canvas.pack() # 若你的gif图带有透明背景,可解开下方注释实现透明启动页(Windows平台生效) # root.wm_attributes("-transparentcolor", canvas["bg"]) # root.wm_attributes("-topmost", True) root.after(5000, root.destroy) root.mainloop()
补充说明
- 代码直接读取图片本身的宽高参数,不需要手动写死尺寸,后续更换其他大小的启动图也能自动适配居中效果
- 若需要启动页始终显示在所有窗口最上层,可保留
root.wm_attributes("-topmost", True)这行代码
内容的提问来源于stack exchange,提问作者gerrard87
相关产品推荐
相关产品推荐

