在 Tkinter 中动态调整图像大小
Dynamically resize images in Tkinter
我有几张图片需要在 Tkinter window 中显示(我可能会使用 canvas 来显示它们 - 可能是标签)。这些图像将占据大约三分之一的屏幕。当用户使用不同尺寸的显示器时,我需要图像屏幕比例保持一致。
所以说用户使用微型显示器时,图像需要在小屏幕上占据相同的照片屏幕比例,当用户使用大型 4K 显示器时。
Tkinter 会自动为我做这件事吗?还是我必须自己实施 - 如果是这样,这可能吗?
我没有任何代码,因为我不知道从哪里开始。我以为我可以使用 PIL 或 pillow,但我对它们还很陌生。
任何帮助将不胜感激,谢谢:)
1) 您需要获取当前屏幕分辨率:How do I get monitor resolution in Python?
2) 然后你需要调整图片的大小(How do I resize an image using PIL and maintain its aspect ratio?) and/or your window (https://yagisanatode.com/2018/02/23/how-do-i-change-the-size-and-position-of-the-main-window-in-tkinter-and-python-3/)
所以代码应该是这样的:
from win32api import GetSystemMetrics
from Tkinter import Tk
screen_width, screen_height = GetSystemMetrics(0), GetSystemMetrics(1)
root = Tk() # this is your window
root.geometry("{}x{}".format(screen_width//2, screen_height//2)) # set size of you window here is example for 1/2 screen height and width
img = Image.open("picture_name.png", "r") # replace with picture path
width, height = screen_width//4, screen_height//4 # determine widght and height basing on screen_width, screen_height
img.resize((width, height), Image.ANTIALIAS)
# todo: create more Tkinter objects and pack them into root
root.mainloop()
这应该可以解决您的问题。关于Tkinter的使用,教程很多,例如:http://effbot.org/tkinterbook/
我有几张图片需要在 Tkinter window 中显示(我可能会使用 canvas 来显示它们 - 可能是标签)。这些图像将占据大约三分之一的屏幕。当用户使用不同尺寸的显示器时,我需要图像屏幕比例保持一致。
所以说用户使用微型显示器时,图像需要在小屏幕上占据相同的照片屏幕比例,当用户使用大型 4K 显示器时。
Tkinter 会自动为我做这件事吗?还是我必须自己实施 - 如果是这样,这可能吗?
我没有任何代码,因为我不知道从哪里开始。我以为我可以使用 PIL 或 pillow,但我对它们还很陌生。
任何帮助将不胜感激,谢谢:)
1) 您需要获取当前屏幕分辨率:How do I get monitor resolution in Python?
2) 然后你需要调整图片的大小(How do I resize an image using PIL and maintain its aspect ratio?) and/or your window (https://yagisanatode.com/2018/02/23/how-do-i-change-the-size-and-position-of-the-main-window-in-tkinter-and-python-3/)
所以代码应该是这样的:
from win32api import GetSystemMetrics
from Tkinter import Tk
screen_width, screen_height = GetSystemMetrics(0), GetSystemMetrics(1)
root = Tk() # this is your window
root.geometry("{}x{}".format(screen_width//2, screen_height//2)) # set size of you window here is example for 1/2 screen height and width
img = Image.open("picture_name.png", "r") # replace with picture path
width, height = screen_width//4, screen_height//4 # determine widght and height basing on screen_width, screen_height
img.resize((width, height), Image.ANTIALIAS)
# todo: create more Tkinter objects and pack them into root
root.mainloop()
这应该可以解决您的问题。关于Tkinter的使用,教程很多,例如:http://effbot.org/tkinterbook/