【问题标题】:Tkinter GUI, Open File .. Button and BMP images .. Error on showing a selected fileTkinter GUI,打开文件 .. 按钮和 BMP 图像 .. 显示所选文件时出错
【发布时间】: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


【解决方案1】:

按钮命令需要 PhotoImage 类的实例。它不能直接显示 PIL 对象。将您的代码更改为:

pil_image = Image.open(tkFileDialog.askopenfilename())
image1 = ImageTk.PhotoImage(pil_image)

【讨论】:

  • 这实际上将图像放入按钮中,我想按下按钮打开,另一个按钮显示它。我使用图片展示吗?
  • @santoznma:我不明白这个问题。您的原始代码试图将图像放入按钮中,这就是我的示例所显示的。无论如何,您的问题的答案是您不能直接显示 PIL 图像,您必须将其转换为 PhotoImage。
  • 这确实有效(将图像放入按钮中)。转换成Photoimage后,如何显示?
  • @santoznma:将其放在标签、按钮中,或将其嵌入画布或文本小部件中。
  • 感谢您的支持!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 2014-09-30
相关资源
最近更新 更多