Search code examples
pythontkinterglobaltkinter-entry

tkinter entry variable from function


This should be easy but I am suffering search fatigue for the answer I need. The code below pops up an input window. I make entries into the entry fields and the function show_entry_fields() gets the input and the window closes. I then want to use the new entry variables in code that follows but they revert back to their initial, global values. I define them as global so I can use them throughout the script, but the entry function fails to change them. How can I get input from users that is then available to the rest of the program?

import tkinter as tk

site = 'cats'
score = 100

def show_entry_fields():
    site = e1.get()
    score = e2.get()
    master.destroy()
    #print(site,score)


master = tk.Tk()
master.columnconfigure(1, weight=1)
tk.Label(master, text="website").grid(row=0)
tk.Label(master, text="Image Ranking").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)

e1.insert(0,site)

e1.grid(row=0, column=1, sticky='EW')
e2.grid(row=1, column=1, sticky='EW')

tk.Button(master, text='Quit', command=master.quit).grid(row=3,  column=0, sticky='W', pady=4)
tk.Button(master, text='Go!', command=show_entry_fields).grid(row=3, column=1, sticky='W', pady=4)
master.mainloop( )

print(site, score)

Solution

  • Does this solve the problem?

    def show_entry_fields():
        global site, score, master
        site = e1.get()
        score = e2.get()
        master.destroy()
    

    At least the print at the end of the program is printing the right answer.