【发布时间】:2014-10-06 11:53:47
【问题描述】:
所以我正在做一个用 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 大小的缩放版本。
我已经搜索了这些,但没有真的有帮助:
【问题讨论】:
-
看起来
image1是一个图像对象,但tk.Button构造函数期望图像的路径,因此它试图在磁盘上找到图像文件的字符串表示形式(并且失败) . -
那么我该如何解决这个问题?
-
@Trengot:你错了。
tk.Button命令需要一个图像对象,而不是文件的路径。 -
@BryanOakley,很公平。我只是通过错误消息。如果我确定我会把它作为答案而不是评论。
标签: python tkinter python-imaging-library