0

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()

3 Answers 3

2

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()
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.