Python tkinter how to get value from an entry box

Question:

I am trying to make a little thing in python like JOpenframe is java and I’m trying to make an entry box. That works fine but when I try to get the value and assign it to variable "t" nothing works. This is what I have:

def ButtonBox(text):
    root = Tk()
    root.geometry("300x150")
    t = Label(root, text = text, font = ("Times New Roman", 14))
    t.pack()
    e = Entry(root, borderwidth = 5, width = 50)
    e.pack()
    def Stop():
        root.destroy()
        g = e.get()
    ok = Button(root, text = "OK", command = Stop)
    ok.pack()
    root.mainloop()
t = ButtonBox("f")

I’ve tried to make "g" a global variable but that doesn’t work. I have no idea how to get the value from this, and I’m hoping someone who does can help me out. Thanks!

Asked By: yavda

||

Answers:

If you want to return the value of the entry box after ButtonBox() exits, you need to:

  • initialize g inside ButtonBox()
  • declare g as nonlocal variable inside inner function Stop()
  • call g = e.get() before destroying the window

Below is the modified code:

from tkinter import *

def ButtonBox(text):
    g = ""   # initialize g
    root = Tk()
    root.geometry("300x150")
    t = Label(root, text = text, font = ("Times New Roman", 14))
    t.pack()
    e = Entry(root, borderwidth = 5, width = 50)
    e.pack()
    def Stop():
        # declare g as nonlocal variable
        nonlocal g
        # get the value of the entry box before destroying window
        g = e.get()
        root.destroy()
    ok = Button(root, text = "OK", command = Stop)
    ok.pack()
    root.mainloop()
    # return the value of the entry box
    return g
t = ButtonBox("f")
print(t)
Answered By: acw1668
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.