Newbie doing lengthy initialization with Tkinter gui

jmdeschamps at gmail.com jmdeschamps at gmail.com
Sun Aug 13 10:01:25 EDT 2006


Maric Michaud wrote:
> Le dimanche 13 août 2006 12:39, Pasi Oja-Nisula a écrit :
>
> > The question is how (or where) can I call my loadImages function right
> > after the mainloop starts? Or is there a better way to do this?
> >
> Seems a good use case for multi-thread, try something like this :
>
> In [28]: import Tix
>
> In [29]: main=Tix.Tk()
>
> In [30]: p=Tix.Meter(main)
>
> In [31]: p.pack()
>
> In [32]: def process(progress) :
>    ....:     from time import sleep
>    ....:     for i in range(10) :
>    ....:         sleep(1)
>    ....:         p.configure(value=float(p.cget('value'))+0.1)
>    ....:
>    ....:
>
>
> In [33]: import thread
>
> In [34]: thread.start_new_thread(process, (p,)) and main.mainloop()
>
> Of course the last line is tricky, the thread should be started by the
> App(Tix.Tk) mainloop.
>
>
> > Pasi
>
> --
> _____________
>
> Maric Michaud
> _____________
>
> Aristote - www.aristote.info
> 3 place des tapis
> 69004 Lyon
> Tel: +33 426 880 097

Tkinter also has a timer-type function called *after*. Use this to call
your init function just befrore the mainloop call. You gui wil show up
and you can then update it to show progress as you wish
No neep for thread or Tix modules...!

Here's a working example:
#################
from Tkinter import *
# Your progress showing function
def showProgress(i):
    # Tell the gui to show some progress here
    obj=c.find_withtag("job")[0]
    c.itemconfig(obj,text="Ok from job is up to "+str(i))
    c.update()

# Your app init function
def doInitOne():
    #Do some init work here
    for i in range(100):
        for j in range(100):
            for k in range(100):
                for m in range(100):
                    a=1
        # Once in a while update the gui
        showProgress(i)

# your main app
root=Tk()
c=Canvas(root,bg="yellow",width=300,height=300)
monobj=c.create_text(100,200,text="Some ",tags="job")
c.pack()
# this will *sleep* one millisec before calling
# your doInitOne function and continue
# with the rest of the code during that sleep time
# in this case just the mainloop
root.after(1, doInitOne)
root.mainloop()




More information about the Python-list mailing list