[Tutor] How to add an Image in Grid mode with Python and Tkinter?

Alan Gauld alan.gauld at yahoo.co.uk
Mon Jul 30 14:26:13 EDT 2018


On 30/07/18 08:24, Matthew Polack wrote:

> I'm trying to simply add an image to our program to make the GUI more
> interesting...but most of the tutorials describe using the 'Pack'
> method.... not the grid method of layout...

That's completely irrelevant since you can add images to widgets
regardless of the layout manager used. In most cases you will
want to use a PhotoImage widget to do it though.

> and apparently you cannot use 'Pack' and 'Grid' in the one program...

Yes you can just not in the same container.
For example a common strategy for building forms based apps
is to have a menubar on top with a toolbar frame packed below
with a data frame packed below that and finally a status
bar frame packed at the bottom.

Within those frames you use the packer for the toolbar buttons,
and for the status bar text. Then you use the grid layout
manager to display the data entry widgets in the centre panel.

So at each container(usually a Frame) level you can only have
a single layout manager, but inside each nested container
you can choose to use the same or a different manager.

And remember there are more than just pack and grid, there
are also place and form(in Tix) (and you can write your own
if you are really keen!)

> Can anyone explain how I could add an image to this program? Or show me an
> example of a simple program that lets someone simply add an image and use
> the grid layout in combination.
import tkinter as tk

top = tk.Tk()
tk.Label(image = "foo.img").grid(row=0,column=0)

top.mainloop)()


Thats about as simple as it gets. But the img file must
be in Tk compatible format.

More generally, use a PhotoImage:

import tkinter as tk

top = tk.Tk()
lbl = tk.Label()
lbl.grid(row=0,column=0)  #could as easily use pack() or place()

img = tk.PhotoImage(file="/path/to/myimg.gif")
lbl['image'] = img

top.mainloop)()

But to get more sophisticated you really want to look
into the PIL/Pillow library and its integration with
Tkinter via the image class. Also look at how the Text
and Canvas widgets deal with images because its slightly
more complex than a simple Label or Button.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list