james hughes
james hughes

Reputation: 617

Return statement not working python 3

The idea of this code is, the user presses the first button and enters what they want, then they press the second button and it prints it out. Can someone please tell me why my return statement is not working? It says that 'variable' is not defined. Thanks in advance for taking the time to read my question.

from tkinter import*

def fun():
    variable = input('Enter Here:')
    return variable


def fun_2():
    print(variable)


window = Tk()
button = Button(text = 'Button', command = fun )
button2 = Button(text = 'Button2', command = fun_2 )
button.pack()
button2.pack()


window.mainloop()

Upvotes: 0

Views: 2464

Answers (3)

Martin Konecny
Martin Konecny

Reputation: 59611

In python when you create a variable inside of a function, it is only defined within that function. Therefore other functions will not be able to see it.

In this case, you will probably want some shared state within an object. Something like:

class MyClass:
  def fun(self):
    self.variable = input('Enter Here:')

  def fun_2(self):
    print(self.variable)

mc = MyClass()

window = Tk()
button = Button(text = 'Button', command = mc.fun )
button2 = Button(text = 'Button2', command = mc.fun_2 )
button.pack()
button2.pack()

Upvotes: 2

Unapiedra
Unapiedra

Reputation: 16197

The problem is in in fun2(). It does not get variable as an input parameter.

def fun_2(variable):
     print(variable)

But note that you have to call fun_2 now with the appropriate argument. Also, as the function stands right now, there is little point in having the function if you just do a print inside of it.

Take away message: variable is not global in Python, and as such you must pass it to each function that wants to use it.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121924

fun() may return a value, but Tkinter buttons don't do anything with that return value.

Note that I used the phrase return a value, not return a variable. The return statement passes back the value of an expression, not the variable variable here. As such, the variable variable is not made into a global that other functions then can access.

Here, you can make variable a global, and tell fun to set that global:

variable = 'No value set just yet'

def fun():
    global variable
    variable = input('Enter Here:')

Since you did use any assignment in fun2, variable there is already looked up as a global, and it'll now successfully print the value of variable since it now can find that name.

Upvotes: 2

Related Questions