[Tutor] about tkinter

Alan Gauld alan.gauld at freenet.co.uk
Tue Sep 5 09:55:41 CEST 2006


Hi Linda,

>> Can you be clearer about what exactly you want to do?
>>
> I want to open two windows with one having the blue triangle and the
> other one having the red triangle (the code is attached). I can not
> figure out how to use toplevel.

Looking at your code it would help the readasbility if you put some
of it into functions like
draw_line(seg,color)
draw_oval(x,y)

Assuming you did this your code would then look a bit like:

root = Tk()
can = Canvas(root,....)
can.pack()
for x,y in points1:
    draw_oval(x,y)
for seg in segs1:
    draw_line(seg,'blue')
for x,y in points2:
    draw_oval(x,y)
for seg in seg2:
    draw_line(seg, 'red')

Now I assume that you want to split the code after the first pair
of figures and create a second window there?

You can use Toplevel just as you do root:

top = Toplevel(root)
can2 = Canvas(top,...)
can2.pack()

Note that because Toplevel inherits from root you only
need the one mainloop() call, usually placed at the end
of your code

Here is a very short example of creating two windows:

>>> from Tkinter import *
>>> win = Tk()
>>> win1 = Toplevel(win)
>>> f = Frame(win)
>>> f.pack()
>>> g = Frame(win1)
>>> g.pack()
>>> Label(f,text="Main").pack()
>>> Label(g,text="Sub").pack()
>>> win.mainloop()

BTW I personally find it best not to pack widgets directly
into the toplevel/root window but to first insert a frame. Then
pack the other widgets(like your canvas or my Labels) into
the frame - it seems to make things behave a little
more predictably.)

HTH,

Alan G. 



More information about the Tutor mailing list