1

I've written a script using tkinker in python. When I run the script, it receives an input and print that to the console. It is working great.

What I wish to do is add any functionality to my existing script in such a way so that after filling in the inputbox when I press the get button, it will print the value in the console and quits automatically. Once again, my existing script is capable of printing values. I need to make that button quit as soon as the printing is done. Any help on this will be highly appreciated.

Here is what I've tried so far:

from tkinter import *

master = Tk()

e = Entry(master)
e.pack()
e.focus_set()

callback = lambda : get_val(e.get())
get_val = lambda item: print(item)  #this extra function is for further usage

Button(master, text="get", width=10, command=callback).pack()

master.mainloop()

This is how the inputbox looks like:

enter image description here

SIM
  • 21,997
  • 5
  • 37
  • 109
  • Possible dup: https://stackoverflow.com/questions/110923/how-do-i-close-a-tkinter-window – Robᵩ Mar 02 '18 at 16:53
  • 3
    Don't use lambda. Use proper functions. It will make debugging much easier. – Bryan Oakley Mar 02 '18 at 16:56
  • Possible duplicate of [How to pass arguments to a Button command in Tkinter?](https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter) – Nae Mar 02 '18 at 18:03
  • How come your provided link contains any such material that may solve the issue described here @Nae? Please read the post and try to compare. – SIM Mar 02 '18 at 22:05

2 Answers2

7

Modify the callback function as:

def callback():
    get_val(e.get()) #Gets your stuff done
    master.destroy() #Breaks the TK() main loop
    exit() #Exits the python console

Here,master.destroy() breaks the master.mainloop() loop and thus terminates the GUI and finally exit() makes it exit the python console.

Ubdus Samad
  • 1,218
  • 1
  • 15
  • 27
3

Maintaining your lambda syntax:

callback = lambda : (print(e.get()), master.destroy())

The key is to call master.destroy().

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Your solution works great as well If I take out `item` from your suggested function. Given plus one. I wish I could accept it as well. Thanks. – SIM Mar 02 '18 at 17:05