I want to use the slider widget to zoom an image in small ranges using float values. I have created the slider and function to zoom the image as below however I get the error "TypeError: an integer is required (got type str)". Any suggestions to get this fixed are welcomed.
def showImage():
img = Image.open('image.png')
img = ImageTk.PhotoImage(img.resize((260, 220), Image.ANTIALIAS))
img_label = Label(frame1, image=img)
img_label.image = img
return img
## function to zoom the image ##
def zoom_img(zoom):
showImage()
newsize = (img.size[0]*zoom,
img.size[1]*zoom)
scaledImg = img.resize(newsize, Image.NEAREST)
newImg = ImageTk.PhotoImage(scaledImg)
img_label.configure(image=newImg)
## scaler widget ##
var = StringVar()
zoom_scale = tk.Scale(root, variable=var, orient='horizontal', from_=220.0, to=440.0, length=100, resolution=20.0, command=zoom_img)
zoom_scale.place(x=1600, y=160)
## Error generated ###
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "c:/Users/DANIEL/Desktop/exp/fcnvmb/butt.py", line 218, in zoom_img
scaledImg = img.resize(newsize, Image.NEAREST)
File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py", line 1780, in resize
return self.convert('RGBa').resize(size, resample, box).convert('RGBA')
File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py", line 1784, in resize
return self._new(self.im.resize(size, resample, box))
TypeError: an integer is required (got type str)
CodePudding user response:
The value that gets passed to the tk.Scale
command
callback is a string. You need to convert it to a float.
def zoom_img(zoom):
zoom = float(zoom)
...
Followup
OK, here's a version that seems to work. I assume you want to keep the image window a constant size, which means you'll also need panning. I've filled in some details you omitted, but this should just cut-and-paste run, once you substitute your image file name.
from tkinter import *
from PIL import Image, ImageTk
def showImage():
img = Image.open('7460.PNG')
img = ImageTk.PhotoImage(img.resize((260, 220), Image.ANTIALIAS))
img_label = Label(root, image=img)
img_label.image = img
img_label.pack()
return img_label
## function to zoom the image ##
def zoom_img(zoom):
global newImg
img = Image.open('7460.PNG')
newsize = (img.size[0]*int(zoom), img.size[1]*int(zoom))
scaledImg = img.resize(newsize, Image.NEAREST)
newImg = ImageTk.PhotoImage(scaledImg)
img_label.configure(image=newImg, width=260,height=220)
root = Tk()
## scaler widget ##
var = StringVar()
zoom_scale = Scale(root, variable=var, orient='horizontal', from_=1, to=20, length=100, resolution=1, command=zoom_img)
img_label = showImage()
zoom_scale.pack()
root.mainloop()