I am trying to create an image library and to call an image from that image library in tkinter
. But this code gives me an error:
This is the image library file img.py
:
from tkinter import *
food_0001 = PhotoImage(file='food_0001.gif')
food_0002 = PhotoImage(file='bg.gif')
This is the file intended to open images stored in img.py
:
from tkinter import *
import img
window = Tk()
window.title('image')
canvas = Canvas(window, width = 800, height = 800)
canvas.pack()
canvas.create_image(0,0, anchor=NW, image=food_0001)
window.mainloop()
It is because PhotoImage()
can only be called after creation of Tk()
.
Suggest to rewrite img.py
to create PhotoImage()
only when it is needed. Below is a sample way to do it:
from tkinter import *
imagelist = {
'food_0001': ['food_0001.png', None],
'food_0002': ['bg.png', None],
}
def get(name):
if name in imagelist:
if imagelist[name][1] is None:
print('loading image:', name)
imagelist[name][1] = PhotoImage(file=imagelist[name][0])
return imagelist[name][1]
return None
Then modify your main program to cater the change:
from tkinter import *
import img
window = Tk()
window.title('image')
canvas = Canvas(window, width=800, height=800)
canvas.pack()
canvas.create_image(0, 0, anchor='nw', image=img.get('food_0001'))
window.mainloop()
Of cause there are many other ways to do it and it depends on your imagination.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With