[英]Tkinter GUI, Open File .. Button and BMP images .. Error on showing a selected file
因此,我正在做一个用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大小的缩放版本。
我搜索了这些,但并没有真正帮助:
button命令需要PhotoImage类的实例。 它不能直接显示PIL对象。 更改代码为:
pil_image = Image.open(tkFileDialog.askopenfilename())
image1 = ImageTk.PhotoImage(pil_image)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.