How Do I Resize Tkinter Widgets As Window Is Resized?
I'm new to python and I'm creating a countdown timer for an event with Python and I noticed that the image within the canvas doesn't fill up the entire screen on larger display's a
Solution 1:
For image re-sizing in Python, check out the Python Image Library (PIL). There are several existing posts on the use of PIL, which helped me to write the code below. With the screen dimensions acquired from the running platform and reference dimensions for "correctly" sized images, it is easy to calculate a re-sizing factor. Then the dimensions needed for the expanded/shrunk display can be obtained by applying this factor to the dimensions of the image at the reference screen size (in this case 270x185). The remainder of the code just scans a folder of the reference images (Assets_dir), opens them and resizes with PIL.Image and then saves the resized image to a new folder.
import PIL.Image
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
width = 1920.0 # default screen width/height stored images are based on.
height = 1200.0
width_resize = screen_width/width # calculate resize factor needed to correctly display on current screen.
height_resize = screen_height/height
new_width = int(width_resize*270)
new_height = int(height_resize*185)
Assets_dir = os.getcwd() + '\\Assets\\'
files = list(os.scandir(Assets_dir))
for file in files:
file_ext = file.name[-3:]
file_basename = file.name[:-4]
if file_ext == 'gif':
temp_image = PIL.Image.open(Assets_dir + file.name)
temp_image = temp_image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
temp_image.save(Assets_dir + r'/resize/' + file.name)
Post a Comment for "How Do I Resize Tkinter Widgets As Window Is Resized?"