[Tkinter-discuss] Tkinter and Threads

Stewart Midwinter stewart.midwinter at gmail.com
Sat Feb 5 16:59:56 CET 2005

Douglas, here's a small app showing threading to update a canvas. 
Pretty simple little app but it may be of use. I found it on a website
that Ed Blake discovered with lots of good example.


On Fri, 4 Feb 2005 18:54:47 -0700, Stewart Midwinter
<stewart.midwinter at gmail.com> wrote:
> Douglas:
> After reading your post I'm reminded of a scene early in Ghostbusters
> I where Venkmann says "whatever you do, don't cross the rays (threads)
> ! That would be very, very, bad! "
> Russell Owen's page of 'common Tkinter pitfalls and how to avoid
> them', at the following URL:
> http://www.astro.washington.edu/rowen/TkinterSummary.html, says that
> "all Tkinter access must be from the main thread (or more precisely,
> from the thread that calls the mainloop). Violating this is likely to
> cause nasty and mysterious symptoms such as freezes and core dumps.
> Yes, this makes combining multi-threading and Tkinter very difficult.
> The only fully safe technique I have found it polling (e.g. use
> 'freeze' from the main loop to poll a threading Queue that your thread
> writes).
> since you have two separate threads both working on the same widgets,
> the surprising thing may not be that you are having difficulties, but
> rather that it worked at all!
> Stewart
> --
> Stewart Midwinter
> stewart at midwinter.ca
> stewart.midwinter at gmail.com

Stewart Midwinter
stewart at midwinter.ca
stewart.midwinter at gmail.com
-------------- next part --------------
# Brownian motion -- an example of a multi-threaded Tkinter program.

from Tkinter import *
import random
import threading
import time
import sys

WIDTH = 400
HEIGHT = 300
SIGMA = 10
BUZZ = 2
FILL = 'red'

stop = 0                                # Set when main loop exits

def particle(canvas):
    r = RADIUS
    x = random.gauss(WIDTH/2.0, SIGMA)
    y = random.gauss(HEIGHT/2.0, SIGMA)
    p = canvas.create_oval(x-r, y-r, x+r, y+r, fill=FILL)
    while not stop:
        dx = random.gauss(0, BUZZ)
        dy = random.gauss(0, BUZZ)
        dt = random.expovariate(LAMBDA)
            canvas.move(p, dx, dy)
        except TclError:

def main():
    global stop
    root = Tk()
    canvas = Canvas(root, width=WIDTH, height=HEIGHT)
    canvas.pack(fill='both', expand=1)
    np = 30
    if sys.argv[1:]:
        np = int(sys.argv[1])
    for i in range(np):
        t = threading.Thread(target=particle, args=(canvas,))
        stop = 1


More information about the Tkinter-discuss mailing list