-1

I've defined a function, but I 'm not able to call the variable from define function to global.

Please help me to solve this problem.

Here is my code:

def pdf_btnClicked():
    PathOfPDF = askopenfile()
    PDFFILE = PathOfPDF.name
    print(PDFFILE)

book = open(PDFFILE, 'rb')
martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

2

As long as you are using Python, you can use the global keyword when declaring a variable on a local scope. Using it will make your variable goes global and your code will look like this:

def pdf_btnClicked():
   global PDFFILE
   PathOfPDF = askopenfile()
   PDFFILE = PathOfPDF.name
   print(PDFFILE)

book = open(PDFFILE, 'rb')

Looking at the code we can inferir that your problem is related to the concept of variable scope.

A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. Basicaly there are two type of variable regarding it's scope:

  1. Inside a function or a block which is called local variables

In this case, if you declare a varible inside a function, you wont be able to use it outside that function. That's exactly your case: you declared the variable PDFFILE inside the pdf_btnClicked function so you will only be able to use the variable inside that. But even so, you are calling the variable outside it. A basic solution for your problem is to so set PDFFILE as global variable, whose explanation follows bellow.

  1. Outside of all functions which is called global variables

Global variables, as the name suggest, are global and can be accessed by all function. If you declare PDFFILE outside the function (and before it) your problem will be solved

Obs.: here we saw the two basics types of variables's scope but it's possible to have more than only two depending on the programming language

Fonts: https://www.tutorialspoint.com/cprogramming/c_scope_rules.htm https://www.w3schools.com/python/python_scope.asp

  • Not sure why you are linking to a tutorial on *C* scoping rules. Python's scoping rules may be similar but there are some key differences that you won't get from knowing C's rules. – Martijn Pieters Nov 04 '20 at 08:47
1

Correct code

def pdf_btnClicked():
    global PDFFILE
    PathOfPDF = askopenfile()
    PDFFILE = PathOfPDF.name
    print(PDFFILE)
    
book = open(PDFFILE, 'rb')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

What you need is global keyword.

PDFFILE = ""
def pdf_btnClicked():
    global PDFFILE
    PathOfPDF = askopenfile()
    PDFFILE = PathOfPDF.name
    print(PDFFILE)

# You need to call `pdf_btnClicked()` function
book = open(PDFFILE, 'rb')
Sumanth Lingappa
  • 464
  • 1
  • 6
  • 15