所以我正在做一个用Python编写的程序,它应该做的是显示一个带有按钮的GUI来打开一个图像文件,然后你应该能够看到那些图像,平移和放大它们。
到目前为止我的代码:
import Tkinter as tk
from PIL import Image, ImageTk
import os, tkFileDialog
button_flag = True
def click():
global button_flag
if button_flag:
button1.config(bg="white")
button_flag = False
else:
button1.config(bg="green")
button_flag = True
root = tk.Tk()
frame1 = tk.Frame(root)
frame1.pack(side=tk.TOP, fill=tk.X)
image1 = Image.open(tkFileDialog.askopenfilename())
button1 = tk.Button(frame1, compound=tk.TOP, width=155, height=55, image=image1, text="optional tet", bg='green', command=click)
button1.pack(side=tk.LEFT, padx=2, pady=2)
button1.image = image1
root.mainloop()
但是当我选择图像时,它会给我一个错误:
Traceback (most recent call last):
File "C:\Users\Joao\Desktop\test3", line 24, in <module>
button1 = tk.Button(frame1, compound=tk.TOP, width=155, height=55, image=image1, text="optional tet", bg='green', command=click)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2106, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2036, in __init__
(widgetName, self._w) + extra + self._options(cnf))
TclError: image "<PIL.BmpImagePlugin.BmpImageFile image mode=P size=1086x1580 at 0x317A648>" doesn't exist
另一件事是我无法在点击打开图像(来自tkFileDialog.askopenfilename()
)然后显示完整图像时配置按钮,而不仅仅是适合gui尺寸的缩放版本。 / p>
我搜索了那些但 不 真的有帮助:
答案 0 :(得分:0)
button命令需要PhotoImage类的实例。它无法直接显示PIL对象。将您的代码更改为:
pil_image = Image.open(tkFileDialog.askopenfilename())
image1 = ImageTk.PhotoImage(pil_image)