Search code examples
pythonimagewindowtkinter

Image in corner of tkinter window in python 3


Is it possible to put a small image in tkinter window for ex. in the right corner of the window, if so how to do it?


Solution

  • You can create a label, put an image in that label, then use place to put it precisely where you want. For example, you can use a relative x and y of 1.0 and an anchor of "se" to put it in the lower-right-hand corner.

    Here is a contrived example:

    import Tkinter as tk
    
    class Example(tk.Frame):
        def __init__(self, *args, **kwargs):
            tk.Frame.__init__(self, *args, **kwargs)
    
            # a simple label, just to show there's something in the frame
            label = tk.Label(self, text="Example of using place")
            label.pack(side="top", fill="both", expand=True)
    
            # we'll place this image in every corner...
            self.image = tk.PhotoImage(data='''
                R0lGODlhEAAQALMAAAAAAP//AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
                AAAAAAAAAAAA\nAAAAACH5BAEAAAIALAAAAAAQABAAQAQ3UMgpAKC4hm13uJnWgR
                TgceZJllw4pd2Xpagq0WfeYrD7\n2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7\n
            ''')
    
            # ... by creating four label widgets ...
            self.nw = tk.Label(self, image=self.image)
            self.ne = tk.Label(self, image=self.image)
            self.sw = tk.Label(self, image=self.image)
            self.se = tk.Label(self, image=self.image)
    
            # ... and using place as the geometry manager
            self.nw.place(relx=0.0, rely=0.0, anchor="nw")
            self.ne.place(relx=1.0, rely=0.0, anchor="ne")
            self.sw.place(relx=0.0, rely=1.0, anchor="sw")
            self.se.place(relx=1.0, rely=1.0, anchor="se")
    
    if __name__ == "__main__":
        root = tk.Tk()
        root.wm_geometry("400x400")
        Example(root).pack(side="top", fill="both", expand=True)
        root.mainloop()