how to call a method on the GUI thread?
<p>I am making a small program that gets the latest revenue from a webshop, if its more than the previous amount it makes a sound, I am using Pyglet but I get errors because its not being called from the main thread. I would like to know how to call a method on the main thread. see error below:</p>

<blockquote>
  <p>'thread that imports pyglet.app' RuntimeError: EventLoop.run() must
  be called from the same thread that imports pyglet.app</p>
</blockquote>

<pre><code>    def work ():
        threading.Timer(5, work).start()
        file_Name = "save.txt"
        lastRevenue = 0
        data = json.load(urllib2.urlopen(''))
        newRevenue = data["revenue"]
        if (os.path.getsize(file_Name) &lt;= 0):
            with open(file_Name, "wb") as f:
                f.write('%d' % newRevenue)
                f.flush()
        with open(file_Name, "rb") as f:
            lastRevenue = float(f.readline().strip())
            print lastRevenue
            print newRevenue
            f.close()
            if newRevenue &gt; lastRevenue:
                with open(file_Name, "wb") as f:
                    f.write('%f' % newRevenue)
                    f.flush()
                    playsound()  


    def playsound():
        music = pyglet.resource.media('cash.wav')
        music.play()
        pyglet.app.run()    

    work()
</code></pre>

<p>It's not particularly strange. <code>work</code> is being executed as a separate thread from where <code>pyglet</code> was imported.</p>

<p><code>pyglet.app</code> when imported sets up a lot of context variables and what not. I say what not because I actually haven't bothered checking deeper into what it actually sets up.</p>

<p>And OpenGL can't execute things out of it's own context (the main thread where it resides). There for you're not allowed to poke around on OpenGL from a neighboring thread. If that makes sense.</p>

<p>However, if you create your own <code>.run()</code> function and use a class based method of activating Pyglet you can start the GUI from the thread.</p>

<p>This is a working example of how you could set it up:</p>

<pre><code>import pyglet
from pyglet.gl import *
from threading import *

# REQUIRES: AVBin
pyglet.options['audio'] = ('alsa', 'openal', 'silent')

class main(pyglet.window.Window):
    def __init__ (self):
        super(main, self).__init__(300, 300, fullscreen = False)
        self.x, self.y = 0, 0

        self.bg = pyglet.sprite.Sprite(pyglet.image.load('background.jpg'))
        self.music = pyglet.resource.media('cash.wav')
        self.music.play()
        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def render(self):
        self.clear()
        self.bg.draw()
        self.flip()

    def run(self):
        while self.alive == 1:
            self.render()

            if not self.music.playing:
                self.alive = 0
            # -----------&gt; This is key &lt;----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

class ThreadExample(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.start()

    def run(self):
        x = main()
        x.run()

Test_One = ThreadExample()
</code></pre>

<p>Note that you still have to start the actual GUI code from within the thread.</p>

<h1>I STRONGLY RECOMMEND YOU DO THIS INSTEAD THO</h1>

<p>Seeing as mixing threads and GUI calls is a slippery slope, I would suggest you go with a more cautious path.</p>

<pre><code>from threading import *
from time import sleep

def is_main_alive():
    for t in enumerate():
        if t.name == 'MainThread':
            return t.isAlive()

class worker(Thread):
    def __init__(self, shared_dictionary):
        Thread.__init__(self)
        self.shared_dictionary
        self.start()

    def run(self):
        while is_main_alive():
            file_Name = "save.txt"
            lastRevenue = 0
            data = json.load(urllib2.urlopen(''))
            newRevenue = data["revenue"]
            if (os.path.getsize(file_Name) &lt;= 0):
                with open(file_Name, "wb") as f:
                    f.write('%d' % newRevenue)
                    f.flush()
            with open(file_Name, "rb") as f:
                lastRevenue = float(f.readline().strip())
                print lastRevenue
                print newRevenue
                f.close()
                if newRevenue &gt; lastRevenue:
                    with open(file_Name, "wb") as f:
                        f.write('%f' % newRevenue)
                        f.flush()
                        #playsound()
                        # Instead of calling playsound() here,
                        # set a flag in the shared dictionary.
                        self.shared_dictionary['Play_Sound'] = True
            sleep(5)

def playsound():
    music = pyglet.resource.media('cash.wav')
    music.play()
    pyglet.app.run()    

shared_dictionary = {'Play_Sound' : False}
work_handle = worker(shared_dictionary)

while 1:
    if shared_dictionary['Play_Sound']:
        playsound()
        shared_dictionary['Play_Sound'] = False
    sleep(0.025)
</code></pre>

<p>It's a rough draft of what you're looking for.<br>
Basically some sort of event/flag driven backend that the Thread and the GUI can use to communicate with each other.</p>

<p>Essentially you have a worker thread (just as you did before), it checks whatever file you want every 5 seconds and if it detects <code>newRevenue &gt; lastRevenue</code> it will set a specific flag to <code>True</code>. Your main loop will detect this change, play a sound and revert the flag back to False.</p>

<p>I've by no means included any error handling here on purpose, we're here to help and not create entire solutions. I hope this helps you in the right direction.</p>

python multithreading audio pyglet