How to override a global variable inside a function?

Viewed 100

Here is code:

from tkinter import *
from tkinter.filedialog import askopenfilename


root = Tk()

p = None

def set_text(text):
    global p

    filePath.delete(0,END)
    filePath.insert(0,text)

    p = filePath.get()

    return


def get_path():
    filename = askopenfilename()
    json1_file = open(filename)
    return filename

root['bg'] = '#fafafa'

root.title('json parser')

root.geometry('500x300')

root.resizable(width=False, height=False)

frame_top = Frame(root, bg='#ffb700', bd=5)

frame_top.place(relx=0.15, rely=0.15, relwidth=0.7, relheight=0.25)

frame_bottom = Frame(root, bg='#ffb700', bd=5)
frame_bottom.place(relx=0.15, rely=0.55, relwidth=0.7, relheight=0.1)


filePath= Entry(frame_top, bg='white', font=30)
filePath.pack(side=LEFT)

b1 = Button(frame_top,text="choose file",command=lambda:set_text(get_path()))
b1.pack(side=RIGHT)
print(p)

info = Label(frame_bottom, text='programm', bg='#ffb700', font=40)
info.pack()

root.mainloop()

I am new to programming and this is my first experience with tkinter. I need the result of the filePath.get() function to use it outside the function. I tried assigning it to p variable as a global variable but it didn't work. What did I do wrong?

1 Answers

No wrong with p variable assigning.P already has value.But you must attention to mainloop() mechanism . In the beginning when program run p has not value.after pressing b1 button p take value but print(p) don't call again because mainloop() just refresh widget no entire of code.

Related