[Tutor] Tkinter: Can's figure out how to put a frame in a second window

Alan Gauld alan.gauld at yahoo.co.uk
Sat Mar 9 06:13:43 EST 2019


On 09/03/2019 02:53, Chris Roy-Smith wrote:

> What is happening is that the contents of the frame appear in the master 
> window. I was expecting them to show in the second window. Also I 
> expected the frame to be sunken, but there is no obvious signs of the 
> frame, not even a colored background.
> 
> What am I doing wrong?

Its a very common mistake in Tkinter.
When you use one of the layout managers, in this case grid()
the return value is always None.

> def NewWindow():
>      sw=Toplevel(master)
>      sw.title('New Window')
>      Label(sw, text='new window').grid(row=0, column=0)
>      sframe=Frame(sw, relief=SUNKEN, bg='red').grid(row=1, column=0)

So you are here assigning None to sframe.

>      Label(sframe, text='Label in a frame').grid(row=2, column=0)
>      Label(sframe, text='Second label in this frame').grid(row=3, column=0)

And when you pass None as the parent to a widget Tk
defaults to the root. So your widgets appear in your main window.

Change the sframe line to two lines:

sframe=Frame(sw, relief=SUNKEN, bg='red')
sframe.grid(row=1, column=0)


and all will be well....

except the sunken relief wont work.
TYhats because the sunken form requires a border width of at least 2
pixels to be visible. So you need to add border=2 (or more) to make
it work.

So the final line should be:

sframe=Frame(sw, border=2, relief=SUNKEN, bg='red')
sframe.grid(row=1, column=0)

As I say its a very common mistake and so, any time weird things
happen, always check that anywhere you assign a widget to a variable
you call the layout manager on a separate line.

HTH
-- 
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