Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a value from a tkinter form

I'm using code where I need to ask the user for input, using a tkinter window (I'm not using tkinter in other parts of the code).

My issue is that I simply need to use the tkinter window to return a value upon pressing the OK button on the form, which will also close down the form. The only way I can get it to work so far is by using a global variable. I've searched for other solutions to this but either they don't return a value (they simply print it) or don't allow passing text for the prompt.

Thanks in advance if you can help with this.

from tkinter import *

def input_text(prompt):

    def ok():
        global ret
        ret = entry.get()
        master.destroy()

    master = Tk()
    lbl = Label(master, text=prompt)
    lbl.pack()
    entry = Entry(master)
    entry.pack()

    entry.focus_set()

    butt = Button(master, text = "OK", width = 10, command = ok)
    butt.pack()

    mainloop()

print("I am here!")
ret=""
input_text("Enter something")

print("ret is:", ret)
like image 473
JJ_ Avatar asked Oct 22 '25 01:10

JJ_


1 Answers

After a good night's sleep I've solved the problem :-)

The solution was to create a class and return the response via an attribute. Here's the code for the archive ... just in case anyone out there has a similar question.

from tkinter import *

class InputForm():
    def __init__ (self, prompt):
        self.prompt = prompt
        self.response = ""

        def ok():
            self.response = entry.get()
            master.destroy()

        master = Tk()
        lbl = Label(master, text=self.prompt)
        lbl.pack()
        entry = Entry(master)
        entry.pack()

        entry.focus_set()

        butt = Button(master, text = "OK", width = 10, command = ok)
        butt.pack()

        mainloop()

abc = InputForm("Enter something").response

print("returned value is:", abc)
like image 76
JJ_ Avatar answered Oct 24 '25 17:10

JJ_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!