Passing variables with continuous functions?
<p>I am using a function to read an analog value from a joystick and update the label on the tkinter screen. This works well but I also want to use that value outside the function to perform if statements with other returned values. Here is what I have so far:</p>

<pre><code>def joystick():
    global joystick_adc
    joystickRead = readadc(joystick_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
    joystickValue = joystickRead
    joy_val.config(text=joystickRead)
    joy_val.after(1000, joystick)
    return joystickValue
</code></pre>

<p>After it is returned I am assigning it to a variable using:</p>

<pre><code>joystickVal = joystick()
</code></pre>

<p>But it only returns the value once and not continuously like I had hoped. Is there something I am doing wrong here??</p>

<p>By far, the simplest solution is to simply make <code>joystickValue</code> a global variable.</p>

<pre><code>def joystick():
    global joystickValue
    ...
    joystickValue = joystickRead
    ...
</code></pre>

<p>Generally speaking, global variables should be avoided. In an event driven program, however, they are a necessity. It would be better to use classes for your application, but it appears that you're not so globals in this case are unavoidable.</p>

<hr>

<p>In your code, it actually <em>is</em> returning the value every time it's called. It's just that it's returning the value to <code>mainloop</code> rather than whatever function called it the first time.  That is because you use <code>after</code> which defers the call to a future date. The code that makes that call in the future is not your code, but rather <code>mainloop</code>. </p>

python python-3.x tkinter