简体   繁体   中英

Python Tkinter - Image not displaying

I'm writing a short script to display a user selected image in a canvas. The image the user selects could be different sizes. In the long run I want to have the application maximise and present scroll bars if the image loaded is larger than the screen resolution, however I have what is most likely a simple problem, the image selected isn't loaded into the Canvas. I just need another set of eyes.

#!/usr/bin/python
# -*- coding: utf-8 -*-

from Tkinter import Tk, Canvas, Frame, Menu, BOTH, NW
import Image 
import ImageTk
import tkFileDialog

appname = "example"

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)   

        self.parent = parent        
        self.initUI()

    def initUI(self):

        self.parent.title( appname )

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar, tearoff=0)
        fileMenu.add_command(label="Open File", command=self.fileOpen)

        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)

    def onExit(self):
        self.quit()

    def fileOpen(self):
    file = tkFileDialog.askopenfile(
        parent=self.parent,
        mode='rb',
        title='Choose a file',
        filetypes=[ ( "Image files",("*.jpg", "*.jpeg" ) )] )

    if file != None:

        self.img = Image.open(file)
        self.tatras = ImageTk.PhotoImage(self.img)

        canvas = Canvas(self, width=self.img.size[0]+20, 
           height=self.img.size[1]+20)
        canvas.create_image(10, 10, anchor=NW, image=self.tatras)
        canvas.pack(fill=BOTH, expand=1)

    def filePref(self):
    self.quit()

def main():

    root = Tk()
    root.geometry("250x150+300+300")
    app = Example(root)
    root.mainloop()  

if __name__ == '__main__':
    main()

Why doesn't the image load into the canvas when selected? I don't get an error displayed. How can I maxmimise the whole window if the image is larger than the initial window size? How can I add scroll bars if the image is larger than screen resolution?

Thanks

I guess the reason you are not seeing the image is format limitations of TK Image class. I suggest using PIL or Pillow which has a TK compatible image class, and has better image format support (You can try opening a GIF file to make sure it is the reason).

To run this code you need python imaging library, and its ImageTk module installed on your machine. In Ubuntu you may install like this:

sudo apt-get install python-imaging-tk

Here is the desired application code (I changed the class structure a bit, but it's just personal preference). Vertical and horizontal scrollbars are enabled for the Canvas as well.

#!/usr/bin/python
# -*- coding: utf-8 -*-

from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog

appname = "example"

class App(object):
    def __init__(self, root=None):
        if not root:
            root = Tk()
        self.root = root
        self.initUI()

    def initUI(self):
        self.root.title(appname)
        menubar = Menu(self.root)
        self.root.config(menu=menubar)
        fileMenu = Menu(menubar, tearoff=0)
        fileMenu.add_command(label="Open File", command=self.fileOpen)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)
        self.canvas = Canvas(self.root)
        self.canvas.pack(side=LEFT, fill=BOTH)
        self.scrollbar_vert = Scrollbar(self.root)
        self.scrollbar_vert.pack(side=RIGHT, fill=Y)
        self.scrollbar_hor = Scrollbar(self.root)
        self.scrollbar_hor.config(orient=HORIZONTAL)
        self.scrollbar_hor.pack(side=BOTTOM, fill=X)

    def onExit(self):
        self.root.quit()

    def fileOpen(self):
        filename = tkFileDialog.askopenfile(
                parent=self.root,
                mode='rb',
                title='Choose a file',
                filetypes=[ ( "Image files",("*.jpg", "*.jpeg", "*.png", "*.gif") ), ("All files", ("*.*"))] )

        if filename == None:
            return
        self.img = Image.open(filename)
        self.photo_image = ImageTk.PhotoImage(self.img)
        self.canvas.pack_forget()
        self.canvas = Canvas(self.root, width=self.img.size[0], height=self.img.size[1])
        self.canvas.create_image(10, 10, anchor=NW, image=self.photo_image)
        self.canvas.pack(side=LEFT, fill=BOTH)
        self.canvas.config(yscrollcommand=self.scrollbar_vert.set)
        self.canvas.config(xscrollcommand=self.scrollbar_hor.set)
        self.canvas.config(scrollregion=self.canvas.bbox(ALL))
        self.scrollbar_vert.config(command=self.canvas.yview)
        self.scrollbar_hor.config(command=self.canvas.xview)

    def run(self):
        self.root.mainloop()

def main():
    root = Tk()
    root.geometry("250x150+300+300")
    app = App(root)
    app.run()

if __name__ == '__main__':
    main()

If you are still having troubles opening PNG or JPG images, this question might help.

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