Simple image viewer

I am new to this site and I am trying to create a simple image viewer in Python 2.7 using Tkinter, but when I try to load an image in it, it shows nothing! I bet it's something awkwardly obvious, but I don't know what happened. I am using Windows XP. Here is my code:

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

root = Tk(className="Image viewer")

canvas_width = 800
canvas_height = 600
root.config(bg="white")

def openimage():
    picfile = tkFileDialog.askopenfilename()
    img = ImageTk.PhotoImage(file=picfile)
    canvas.create_image(0,0, anchor=NW, image=img) 

yscrollbar = Scrollbar(root)
yscrollbar.pack(side=RIGHT, fill=Y)

xscrollbar = Scrollbar(root, orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X)

canvas = Canvas(root, width=canvas_width, height=canvas_height, yscrollcommand=yscrollbar.set, xscrollcommand=xscrollbar.set)
button = Button(root,text="Open",command=openimage)
button.pack(side=BOTTOM)
canvas.pack(side=TOP)
yscrollbar.config(command=canvas.yview)
xscrollbar.config(command=canvas.xview)

mainloop()

Update: it works when I delete the file browser and give it the path to the file, but I want the file browser to work, and using the shortcut it works, but the scroll bars do not work with it, and I want to be able to scroll the image.

+4
source share
2 answers

TKinter PhotoImage Class", PhotoImage , .

, :

img = None

def openimage():
    global img

    picfile = tkFileDialog.askopenfilename()
    img = ImageTk.PhotoImage(file=picfile)
    canvas.create_image(0,0, anchor=NW, image=img) 

(, canvas)

def openimage():
    picfile = tkFileDialog.askopenfilename()
    canvas.img = ImageTk.PhotoImage(file=picfile)
    canvas.create_image(0,0, anchor=NW, image=canvas.img) 

: ,

def openimage():
    picfile = tkFileDialog.askopenfilename()
    if picfile:
        canvas.img = ImageTk.PhotoImage(file=picfile)
        canvas.create_image(0,0, anchor=NW, image=canvas.img) 

scrollregion,

def openimage():
    picfile = tkFileDialog.askopenfilename()
    if picfile:
        canvas.img = ImageTk.PhotoImage(file=picfile)
        canvas.create_image(0,0, anchor=NW, image=canvas.img) 
        canvas.configure(canvas, scrollregion=(0,0,canvas.img.width(),canvas.img.height()))
+4

, :

def openimage():
    try:
        Artwork.destroy()
    except Exception:
        pass
    picfile = tkFileDialog.askopenfilename()
    img = ImageTk.PhotoImage(file=picfile)
    #canvas.create_image(0,0, anchor=NW, image=img)
    Artwork=Label(root,image=img)
    Artwork.img=img
    Artwork.pack(side=BOTTOM)#do packing urself


, .

0

All Articles