关于#python#的问题:程序窗口大小是这样的我想让程序将图片尽量按照原比例把图片作为背景

img


图片大小是这样的

img


程序窗口大小是这样的
我想让程序将图片尽量按照原比例把图片作为背景,怎么做?
模块:tkinter

下面是根据窗口大小缩放图片居中显示,如果需要平铺占满屏幕,只要把 > 改成 < 就可以了。


from tkinter import *
from PIL import Image, ImageTk

screen_width=1300
screen_height=500
im = Image.open(r"欢迎页.gif")
im_width, im_height = im.size
if im_width/screen_width > im_height/screen_height:
    new_width, new_height = screen_width, int(im_height*screen_width/im_width)
else:
    new_width, new_height = int(im_width*screen_height/im_height), screen_height
im = im.resize((new_width,new_height))

root = Tk()
root.geometry(f'{screen_width}x{screen_height}')
bg = ImageTk.PhotoImage(im)
img_lb = Label(root, image=bg)
img_lb.pack()
root.mainloop()

不过我看你使用的是gif图片,但这样直接放上去gif是不会动的,需要设定一个程序才行。可以参考我写的关于掷骰子的博客。
Python动画制作:用tkinter模拟掷骰子_请叫我问哥的博客-CSDN博客_python tkinter 动画