andrepogg andrepogg - 1 month ago 15
Python Question

askopenfilename tkinter functions and globals

I'm trying to do something to let the users of my company to change their default signature of the email with some personalization.

So I don't understand why when I click this button:

Button(master, text='Insert Image',command=insert_image).grid(row=12,column=1,sticky=W,pady=4)


It calls this:

global image_path

def insert_image():
image_path = filedialog.askopenfilename(initialdir="X:\\", title="Select the image you want to add")
image_path = 'X:\\' + str(image_path)


It lets me choose the file and it seems to store it in the variable, but later, when I have to use the variable here:

if image_path != "":
signature.write('<br><br><img src="{}" alt="prova"><br><br>\n'.format(image_path))


It gives

NameError: name 'image_path' is not defined


What am I doing wrong?

Answer

You need to create your variable in global scope and then use global inside your function.

image_path = ""

def insert_image():
    global image_path
    image_path = filedialog.askopenfilename(...)
    ...
Comments