簡體   English   中英

Tkinter GUI,打開文件..按鈕和BMP圖像..顯示所選文件時出錯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM