Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

python - 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...