我想使用滑塊小部件使用浮點值在小范圍內縮放影像。我創建了滑塊和函式來縮放影像,如下所示,但是我收到錯誤“TypeError:需要一個整數(獲取型別 str)”。歡迎提出任何解決此問題的建議。
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)
uj5u.com熱心網友回復:
傳遞給tk.Scale command回呼的值是一個字串。您需要將其轉換為浮點數。
def zoom_img(zoom):
zoom = float(zoom)
...
跟進
好的,這是一個似乎可以作業的版本。我假設您希望影像視窗保持恒定大小,這意味著您還需要平移。我已經填寫了一些你省略的細節,但是一旦你替換了你的影像檔案名,這應該只是剪切和粘貼運行。
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/468255.html
上一篇:Tkinter拖放滑鼠指標問題
