Python Tkinter PhotoImage

This is the code format that I currently have:

import Tkinter as tk class mycustomwidow: def __init__(self,parent,......) ...... ...... tk.Label(parent,image=Myimage) tk.pack(side='top') def main(): root=tk.Tk() mycustomwindow(root) root.mainlopp() if __name__ == '__main__': main() 

My problem: where should I declare the Myimage photo that I used in mycustomwindow class?

If I put Myimage=tk.PhotoImage(data='....') before root=tk.Tk() , as shown below, it will give me an error too early to create image , since we cannot create an image in front of the root window .

 import Tkinter as tk Myimage=tk.PhotoImage(data='....') class mycustomwidow: def __init__(self,parent,......) ...... ...... tk.Label(parent,image=Myimage) tk.pack(side='top') def main(): root=tk.Tk() mycustomwindow(root) root.mainlopp() if __name__ == '__main__': main() 

If I put Myimage=tk.PhotoImage(data='....') in the main() function like this, it says that it cannot find the Myimage image in the class mycustomwindow .

 import Tkinter as tk class mycustomwidow: def __init__(self,parent,......) ...... ...... tk.Label(parent,image=Myimage) tk.pack(side='top') def main(): root=tk.Tk() Myimage=tk.PhotoImage(data='....') mycustomwindow(root) root.mainlopp() if __name__ == '__main__': main() 

Is there anything bad in my code structure? Where should I declare Myimage so that it can be used in the class mycustomwindow ?

+4
source share
1 answer

No matter where you declare the image, yet

  • you create it after initializing Tk() (the problem is in your first approach)
  • the image is in the variable area when you use it (problem in the second approach)
  • image object does not receive garbage collection (another common trap )

If you define an image in your main() method, you need 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() 

In addition, you can completely abandon the main() method by 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 the __init__ method, but be sure to use the self keyword to bind it to your Frame object so that it doesn't get 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 
+8
source

Source: https://habr.com/ru/post/1492453/


All Articles