简体   繁体   中英

Tkinter GUI, Open File .. Button and BMP images .. Error on showing a selected file

So I'm doing a program that is written in Python and what it should do is Displaying a GUI with a button there to open a image file, and then you'll should be able to see those image, pan and zoom on them.

Heres my code so far:

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()

But when I choose the image it gets me an error:

 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

Other thing is that I can't configure a button to when clicked open an image (from a tkFileDialog.askopenfilename() ) and then showing the full image, not just a zoomed version fitted to the gui size.

I've searched those but did not really help:

The button command requires an instance of the PhotoImage class. It cannot directly display a PIL object. Change your code to be this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM