gert <gert.cuyk...@gmail.com> writes:

> 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 :)
>
I have been using the following scheme:
  - Pass the root object to the thread object when creating the object
  - Define a event_handler: root.bind('<<SomeEvent>>', evt_handler) in
    the main thread.

  - When the thread has done something that the GUI part should now
    about, signal an event in the thread:
        root.event_generate('<<SomeEvent>>')    (no other arguments)

  - Call a method of the thread object in the event handler e.g. to get
    some data from a queue object.

This ensures that only the main thread accesses Tkinter-related things.

from Tkinter import *
from threading import Thread

import Queue
import time

class Weegbrug(Thread):
    def __init__(self, gui, file_name):
        Thread.__init__(self)
        self.gui = gui
        self.queue = Queue.Queue()
        self.file_name = file_name
        
    def run(self):
        while True:
            with open(self.file_name, 'r') as f:
                for line in f:
                    self.queue.put(line)
                    self.gui.event_generate('<<LineRead>>')
                    time.sleep(0.5)

    def get_line(self):
        return self.queue.get()

root = Tk()
v = StringVar()
v.set("00000")
w = Weegbrug(root, '/tmp/test.py')

def evt_handler(*args):
    v.set(w.get_line())
root.bind('<<LineRead>>', evt_handler)

tx = Label(root, textvariable=v, width=100, bg="yellow", font=("Helvetica", 20))
tx.pack(expand=YES, fill=BOTH)
root.title("Weegbrug")

# root.overrideredirect(1)
# root.geometry("%dx%d+0+0" % (root.winfo_screenwidth(),
# root.winfo_screenheight()))

# Don't start before there's a handler installed
w.start()
root.mainloop() 
Jani Hakala
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to