【发布时间】:2020-09-05 05:38:49
【问题描述】:
from PIL import Image
from tkinter import *
def wider():
global photo,lbpic
pic = photo.get()
adj = Image.open(pic)
width,height = adj.size
new_pic = adj.resize((width*2,height))
new_pic.save('Wider'+pic)
lbpic['image'] = new_pic
lbpic.image = new_pic
def taller():
global photo,lbpic
pic = photo.get()
adj = Image.open(pic)
width,height = adj.size
new_pic = adj.resize((width,height*2))
new_pic.save('Taller'+pic)
lbpic['image'] = new_pic
lbpic.image = new_pic
def rotateangle():
global photo,lbpic,var
pic = photo.get()
adj = Image.open(pic)
angle = var.get()
result = adj.rotate(angle)
result.save('rotated'+angle+pic)
lbpic['image'] = result
lbpic.image = result
def rotate():
global photo,lbpic
var = StringVar()
var.set(90)
rb1 = Radiobutton(win,text='90',variable=var,value=90,command=rotateangle)
rb1.place(x=100,y=110)
rb2 = Radiobutton(win,text='180',variable=var,value=180,command=rotateangle)
rb2.place(x=100,y=140)
rb3 = Radiobutton(win,text='270',variable=var,value=270,command=rotateangle)
rb3.place(x=100,y=170)
win = Tk()
win.title('Photo adjust')
win.geometry('400x400')
lb = Label(win,text='Select a photo')
lb.place(x=100,y=20)
photo = StringVar()
en = Entry(win,textvariable=photo,width=30)
en.place(x=100,y=50)
btn = Button(win,text='Wider',command=wider)
btn.place(x=100,y=80)
btn2 = Button(win,text='Taller',command=taller)
btn2.place(x=150,y=80)
btnrotate = Button(win,text='Rotate',command=rotate)
btnrotate.place(x=200,y=80)
lbpic = Label(win,image='')
lbpic.place(x=150,y=200)
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "E:/Python/Python Projects Fun/photo_shop.py", line 7, in wider
adj = Image.open(pic)
AttributeError: type object 'Image' has no attribute 'open'
对于这个程序,我想选择一张图片来改变按钮内的不同效果。但是我无法使用Image.open(pic) 打开图像,但我已经彻底检查了图像模块具有open 方法的文档。我遵循了文档,但我不明白问题出在哪里?还是版本问题?
【问题讨论】:
-
您使用的是
tkinter.Image而不是PIL.Image,因为from tkinter import *覆盖from PIL import Image。交换两个导入语句。您还需要将PhotoImage实例而不是Image分配给小部件。 -
您的问题说明了为什么
import *不是首选。见PEP 8 -- Style Guide for Python Code
标签: python user-interface tkinter python-imaging-library