Home > Enterprise >  Tkinter - Return a Value and Close GUI
Tkinter - Return a Value and Close GUI

Time:09-02

I am a total newbie with GUIs and also tkinter.

I am trying to get 2 inputs from user through a GUI which I implemented with tkinter. After the user give inputs and press the button, I want to return to these 2 inputs and keep doing something else with these 2 inputs. I have checked Return values of Tkinter text entry, close GUI but it did not work for my case.

What I have tried is this:

_Gui.py

import tkinter as tk

def get_input():
    entry1 = entry1.get()
    entry2 = entry2.get()
    return entry1, entry2

root = tk.Tk()
root.geometry("320x240 800 300")

label1 = tk.Label(text="Label1")
label1.config(font=('Helvetica bold',16))
label1.pack()
entry1 = tk.Entry(root)
entry1.config(font=('Helvetica bold',16))
entry1.pack()
label2 = tk.Label(text="Label2")
label2.config(font=('Helvetica bold',16))
label2.pack()
entry2 = tk.Entry(root)
entry2.config(font=('Helvetica bold',16))
entry2.pack()

button = tk.Button(root, text="Start", command=get_input)
button.config(font=('Helvetica bold',16))
button.pack()

root.mainloop()

And in main.py:

import _Gui as gui

if __name__ == "__main__":
    a, b = gui.get_input()
    something_else(a, b)

But it also did not work.

Thanks for your help in advance!

CodePudding user response:

You can use root.destroy() to destroy the window, but the function get_input() will execute twice after you pressed the button (the other is after the window is destroyed, in your "main.py"), so if you destroyed the window in the first execution, you can't use entry1.get().

I suggest you use this:

(_Gui.py)

import tkinter as tk

root = tk.Tk()
root.geometry("320x240 800 300")

def get_input():
    global a, b
    a = entry1.get()
    b = entry2.get()
    root.destroy()

label1 = tk.Label(text="Label1")
label1.config(font=('Helvetica bold',16))
label1.pack()
entry1 = tk.Entry(root)
entry1.config(font=('Helvetica bold',16))
entry1.pack()
label2 = tk.Label(text="Label2")
label2.config(font=('Helvetica bold',16))
label2.pack()
entry2 = tk.Entry(root)
entry2.config(font=('Helvetica bold',16))
entry2.pack()

button = tk.Button(root, text="Start", command=get_input)
button.config(font=('Helvetica bold',16))
button.pack()

(main.py)

import _Gui as gui

if __name__ == "__main__":
    gui.root.mainloop()
    something_else(gui.a, gui.b)

(Sorry, my English is not very well.)

  • Related