Threading and tkinter

Scott David Daniels Scott.Daniels at Acm.Org
Wed Feb 18 20:02:55 EST 2009

gert wrote:
> After reading the docs and seeing a few examples i think this should
> work ?
> Am I forgetting something here or am I doing something stupid ?
> Anyway I see my yellow screen, that has to count for something :)
Try this:
from __future__ import with_statement

import time
import Tkinter
import Tkconstants as TK
import threading

class Weegbrug(threading.Thread):
     def __init__(self, frame, var, filename):
         self.frame = frame
         self.var = var
         self.filename = filename

     def run(self):
         with open(self.filename, 'r') as f:
             for n, line in enumerate(f):
                 # the tricky bit:
                 self.frame.after(100, self.var.set, line.strip())

def main(filename):
     root = Tkinter.Tk()
     svar = Tkinter.StringVar(root)
     frame = Tkinter.Frame(root, relief=TK.RIDGE, borderwidth=2)
     frame.pack(fill=TK.BOTH, expand=1)
     label = Tkinter.Label(frame, textvar=svar, bg='yellow',
                           font=('Helvetica', 16))
     label.pack(fill=TK.X, expand=1)
     button = Tkinter.Button(frame, text="Exit", command=root.destroy)
     reader = Weegbrug(frame, svar, filename)
     button = Tkinter.Button(frame, text="Go", command=reader.start)

if __name__ == '__main__':

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list