Home > Net >  Python tkinter how to get value from an entry box
Python tkinter how to get value from an entry box

Time:09-27

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!

CodePudding user response:

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)
  • Related