简体   繁体   中英

Global variables in Python with file names

I am writing a Python 3 program with Tkinter, which is running under Windows 8.1.

I need to select two folders which will be used together in another function. Currently, I have two select file buttons, which open the select folder dialog box:

def select_file_1(self):
    global first_file
    first_file = filedialog.askdirectory()

def select_file_2(self):
    global second_file
    second_file = filedialog.askdirectory()

These work correctly: whenever the buttons are clicked, it comes up and asks for a directory.

Then, there is only one other time the first_file and second_file variables are used, which I also note as global variables before using them. This is when another button is selected:

def create_composite(self):
    global first_file
    global second_file

    f1 = open(first_file, "r")
    f2 = open(second_file, "r")

However, this results in the following error: NameError: name 'first_file' is not defined when trying to read the line above beginning with f1 = open .

If it helps for clarity, here is the relevant part of my interface in the screenshot below. select_file_1 is called by clicking the first choose file and select_file_2 is called by clicking the second choose file. Then, create_composite is called by clicking create class.

为清晰起见

The snippets you have posted work correctly, so long as select_file_1() and select_file_2() are called before create_composite .

If you are still having problems you need to create a complete, small, working bit of code that you can post so others can see the problem.

Oh, and filedialog.askdirectory returns the name of a directory, not of a file -- trying to open that is not a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM