Tkinter中1920x1080图片显示被缩放问题求助
问题:Tkinter窗口中1920x1080图片被缩放显示
我有一张1920x1080分辨率的图片,想在同尺寸的Tkinter窗口中原样展示,但实际显示时图片被缩放了。
我的代码
accountSystem = Tk() accountSystem.rowconfigure(0, weight = 1) accountSystem.columnconfigure(0, weight = 1) accountSystem.geometry('1920x1080') accountSystem.title('ACCOUNT SYSTEM') signin_bgImage=ImageTk.PhotoImage(file = 'images/sign_in.jpg') signin_bgLabel=Label(sign_in, image = signin_bgImage) signin_bgLabel.place(x=0, y=0) accountSystem.resizable(0,0) accountSystem.mainloop()
对比图
- 原始图片:

- 实际显示效果:

解决方法
1. 修正代码中的变量错误
代码里Label(sign_in, ...)的sign_in是未定义变量,必须替换为窗口实例accountSystem,否则会直接报错。
2. 处理高DPI缩放问题
Windows系统下Tkinter默认跟随系统DPI缩放,导致你设置的1920x1080窗口实际尺寸被调整,进而图片被拉伸。可以通过以下代码禁用DPI感知:
import ctypes ctypes.windll.shcore.SetProcessDpiAwareness(1)
3. 让Label尺寸匹配图片
创建Label时直接指定图片的宽高,避免Tkinter自动调整尺寸:
# 获取图片实际像素尺寸 img_w = signin_bgImage.width() img_h = signin_bgImage.height() signin_bgLabel = Label(accountSystem, image=signin_bgImage, width=img_w, height=img_h)
4. 防止图片被垃圾回收
PhotoImage对象如果没有持久引用会被Python回收,导致图片不显示,需要给它绑定一个窗口级别的引用:
accountSystem.bg_img = signin_bgImage
完整修正代码
import tkinter as tk from PIL import Image, ImageTk import ctypes # 禁用DPI自动缩放(仅Windows系统需要) ctypes.windll.shcore.SetProcessDpiAwareness(1) accountSystem = tk.Tk() accountSystem.geometry('1920x1080') accountSystem.title('ACCOUNT SYSTEM') accountSystem.resizable(0, 0) # 加载图片 signin_bgImage = ImageTk.PhotoImage(file='images/sign_in.jpg') # 创建匹配尺寸的Label signin_bgLabel = tk.Label(accountSystem, image=signin_bgImage, width=signin_bgImage.width(), height=signin_bgImage.height()) signin_bgLabel.place(x=0, y=0, anchor='nw') # 保留图片引用,防止被回收 accountSystem.bg_img = signin_bgImage accountSystem.mainloop()
内容的提问来源于stack exchange,提问作者zeepaul
相关产品推荐
相关产品推荐

