Python Tkinter PhotoImage
This is the format of code I currently have: import Tkinter as tk class mycustomwidow: def __init__(self,parent,......) ...... ...... tk.Label(parent,i
Solution 1:
It does not matter much where you declare the image, as long as
- you create it after initializing
Tk()
(the problem in your first approach) - the image is in the variable scope when you are using it (the problem in your second approach)
- the image object does not get garbage-collected (another common pitfall)
If you define the image in your main()
method, then you will have to make it global
class MyCustomWindow(Tkinter.Frame):
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
Tkinter.Label(self, image=image).pack()
self.pack(side='top')
def main():
root = Tkinter.Tk()
global image # make image known in global scope
image = Tkinter.PhotoImage(file='image.gif')
MyCustomWindow(root)
root.mainloop()
if __name__ == "__main__":
main()
Alternatively, you could drop your main()
method entirely, making it global automatically:
class MyCustomWindow(Tkinter.Frame):
# same as above
root = Tkinter.Tk()
image = Tkinter.PhotoImage(file='image.gif')
MyCustomWindow(root)
root.mainloop()
Or, declare the image in your __init__
method, but make sure to use the self
keyword to bind it to your Frame
object so it is not garbage collected when __init__
finishes:
class MyCustomWindow(Tkinter.Frame):
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
self.image = Tkinter.PhotoImage(file='image.gif')
Tkinter.Label(self, image=self.image).pack()
self.pack(side='top')
def main():
# same as above, but without creating the image
Post a Comment for "Python Tkinter PhotoImage"