Search code examples
pythonimagetkinterwindowframe

How do I place an image in the same window in Tkinter?


I am trying to place the image in the same window but it opens up in a new window and I can't figure out why. I've tried google but couldn't find anything to help me. How do I specify the image should be placed in the initial window that opens up instead of its own separate window?

import Tkinter as tk
import io
import base64
# Import the function for downloading web pages
from urllib import urlopen

# Import the regular expression function
from re import findall

# Import the Tkinter functions
from Tkinter import *

# Import Python's HTML parser
from HTMLParser import *
class MainWindow(tk.Frame):
        root = tk.Tk()

        def __init__(self, *args, **kwargs):
            tk.Frame.__init__(self, *args, **kwargs)

        def createimage(self):  
            # a little more than width and height of image
            w = 520
            h = 320
            x = 80
            y = 100
            # use width x height + x_offset + y_offset (no spaces!)
            # this GIF picture previously downloaded from tinypic.com
            image_url = "http://i46.tinypic.com/r9oh0j.gif"
            image_byt = urlopen(image_url).read()
            image_b64 = base64.encodestring(image_byt)
            self.photo = tk.PhotoImage(data=image_b64)
            # create a white canvas
            #topframe = Frame(root)
            cv = tk.Canvas(bg='white')
            cv.pack(side='top', expand='yes')
            # put the image on the canvas with
            # create_image(xpos, ypos, image, anchor)
            cv.create_image(10, 10, image=self.photo, anchor='nw')

if __name__ == "__main__":
    root = tk.Tk()
    main = MainWindow(root)
    root.geometry("400x300")
    main.pack(side="top", fill="both", expand=True)
    main.createimage()
    root.mainloop()

Solution

  • 1. Why does it open up in a separate window?

    You need to pass a master to each constructor. This should be the widget (Tk, Frame, Toplevel, Canvas, ...) that the new widget should be placed inside. Like this:

    tk.Canvas(master = self, g='white')
    tk.PhotoImage(master = self, data=image_b64)
    

    When the master is destroyed, widgets with it as master are also destroyed.

    2. In which window does it open up?

    Tkinter has the default root, the first window which is created. This window is used for any widget you do not pass a master to.

    i.e. the first root = tk.Tk()