How do you create a gtk window in python and also have code running in the background?
<p>I am trying to create a GUI window with a web address inside (a video stream in this case) while also having some additional code running in the background that communicate with the GPIO ports on a Raspberry Pi. I can get the window to work but the background code only starts when the window is closed. Or if I reverse the order of the code the GPIO code stops working when the window is open. Here is some example code. </p>

<pre><code>import gtk

import webkit

import gobject

import RPi.GPIO as GPIO

from time import sleep

import os

ip = raw_input("Enter the last 3 digits of IP address: ")

awesome = "http://192.168.0." + ip + ":9090/stream"

print awesome

os.system("sudo uv4l -nopreview --auto-video_nr --driver raspicam --encoding mjpeg --width 640 --height 480 --framerate 30 --server-option '--port=9090' --server-option '--max-queued-connections=30' --server-option '--max-streams=25' --server-option '--max-threads=29'")

gobject.threads_init()

win = gtk.Window()

win.connect('destroy', lambda w: gtk.main_quit())

bro = webkit.WebView()

bro.open(awesome)

win.add(bro)

win.show_all()

gtk.main()

GPIO.setmode(GPIO.BOARD)

GPIO.setup(38, GPIO.OUT)

GPIO.setup(40, GPIO.OUT)

GPIO.setup(37, GPIO.OUT)

GPIO.setup(35, GPIO.OUT)

GPIO.output(38, GPIO.HIGH)

GPIO.output(40, GPIO.LOW)

GPIO.output(37, GPIO.LOW)

GPIO.output(35, GPIO.HIGH)

sleep(2)
</code></pre>

<p><code>gtk.main()</code> runs till you close window (it is call "main loop" or "event loop" and it does everything in GUI program - get key/mouse event, send it to widgets, redraw widgets, run functions when ypu press button, etc.). </p>

<p>You have to use <code>Threading</code> to run (long-running) code at the same time or use some <code>Timer</code> class in GUI to execute some code periodically.</p>

python raspberry-pi gtk