2

I have defined a function that will get a value from the user input. It's a path (based on the appJar's .directoryBox). I have put the code for the directory box to popup inside a function so that it will show when a button is pressed. However, I cannot seem to use the value outside of the function.

The important part of the code looks like this:

def dirfunction(button):
    dirr = app.directoryBox('box')
    app.setEntry('Directory', dirr)
    app.showButton('Search')
    return dirr

def searchfunction(button):
    if button == 'Search':
        findBigfile.findBigFiles(dirr, mbSize)


mbSize = app.addLabelEntry('Size in MB')
app.addLabelEntry('Directory')
app.setLabelWidth('Size in MB', '10')
app.setLabelWidth('Directory', '10')

app.addButton('Choose Directory', dirfunction)
app.addButton('Search', searchfunction)
app.hideButton('Search')

app.go()

I try to use the 'dirr' variable outside of the dirfunction, but I cannot make it work. It only works within.

EDIT: I also cannot make the app.directoryBox outside of the function, as that will cause that popup to occur directly when the app is opened.

DavidG
  • 24,279
  • 14
  • 89
  • 82
Anton Ödman
  • 451
  • 3
  • 7
  • 17

1 Answers1

6

dirr is a local variable, it only can be seen inside the context in which is defined (in your case inside the function dirfunction, it doesn't exists outside it).

To be able to see outside you have to declare it outside.

dirr = None

And after of this, access to it from inside the function, in python 2 it's done by using global:

def method():
    global dirr # you have to declare that you'll use global variable 'dirr'
    dirr = "whatever"

And now:

print `dirr` 

will print:

whatever
inigoD
  • 1,681
  • 14
  • 26
  • 2
    It might be worth reading [why are global variables evil](https://stackoverflow.com/questions/19158339/why-are-global-variables-evil) for future reference... – DavidG Jun 28 '17 at 12:58