(no subject)
Jeff Shannon
jeff at ccvcorp.com
Fri Aug 17 12:29:27 EDT 2001
moonlite56 at yahoo.com wrote:
> How do you predefine a function? I want to change an image in a
> canvas and update it, but it (of course) comes up the error that the
> canvas is "referenced before assignment." :) I know there's a way to
> predefine the function at the beginning of my program but actually
> define it later on, but I don't know how. Can someone else help?
There's a fairly simple fix to your immediate problem, but there's also a
better way of doing things. The quick fix first--just make your function
take an argument, instead of trying to reference the global canvas object
before it's created. Thus:
> from Tkinter import *
> import Image,ImageTk
>
> def changeimage():
def changeimage(mycanvas):
> cKuti3.delete(myimage)
> iKuti3 =
> ImageTk.PhotoImage(Image.open("outfit/pinkvest.gif"))
> cKuti3 = cpic.create_image(0, 0, anchor = NW, image = iKuti3)
cKuti3 = mycanvas.create_image(0, 0, anchor=NW, image=iKuti3)
> top = Tk()
[trimming unchanged code]
> changeimage()
changeimage(cpic)
> top.mainloop()
With those changes, this code should run. In the longer term, however,
you've still got the problem of using global variables to refer to
everything. I'd suggest creating a class (MyPicture or whatever),
setting the canvas and various images as attributes of that class, and
make changeimage() and other such functions methods of the class. This
should make for a much simpler design, especially if your program
continues to grow--it's much more flexible and robust than using a slew
of global variables.
Hope that helps...
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list