0

With this below Python code, I wanted to

  1. type "exit"
  2. press "enter" key from keyboard
  3. Close the tkinter window

But post typing "exit" and pressing "Enter" key from keyboard, the "tk window" is not closing.

And the Code is:

import tkinter as tk

window = tk.Tk()

greeting = tk.Label(text = "Test Tk window Frame")
user_input = tk.Text()

user_input.pack()
greeting.pack()

   
def chat(event=None):
    inputmsg = user_input.get(tk.END)
    if inputmsg is None or inputmsg == "": 
        return None

    if inputmsg.lower() == "exit"
        inputmsg.bind('<Return>', lambda e: window.destroy()) # NOT Working
        #window.destroy() # Not Working
        return None

user_input.bind("<Return>", chat) # NOT Working out

window.mainloop()

My intention is to Bind ONLY RETURN KEY and not with a Button. As I'm new to Python with tkinter, Can anyone please share any thought/ ref on this?

Thank you.

Rinku
  • 1
  • 4
  • Hi, welcome to SO! Try to put `print('input you typed:', inputmsg)` after an assignment of `inputmsg`. Does this help to identify your problem better? – mathfux Aug 16 '20 at 20:17
  • You have given a clue. When I put print('input you typed:', inputmsg) after an assignment of inputmsg, I'm getting nothing. So, where am I doing wrong...still wondering. Little more clue can help a lot. – Rinku Aug 17 '20 at 06:05

1 Answers1

1

The source of problem is incorrect fetch of the entry text. So inputmsg is never exit after you enter it. You should use:

user_input.get(1.0, "end-1c")

Read this answer and its comments for further details about these parameters

UPDATE: if only the last line is required you can set your parameters in two ways:

user_input.get("end-5c", "end-1c") #extract 4 symbols before the last (which is '\n')
user_input.get("end-1c linestart", "end-1c lineend") #extract the last line from start to end
mathfux
  • 5,759
  • 1
  • 14
  • 34
  • Yes I got that inputmsg is never exit. But when I tried this, the tkinter window is not closing. certainly still it's not getting the last line with "exit" word. How to get the last string "exit" from entire chat texts? – Rinku Aug 17 '20 at 06:11
  • It actually does in case you use backspaces to leave only the word 'exit' on your chat. – mathfux Aug 17 '20 at 09:05
  • I guess you are able to do much more on yourself here. If a meaning of `1.0` and `end-1c` is clear for you, just use trial and error method and replace `1.0` with `end-2c`, `end-3c` and so on and look how a value of `inputmsg` varies. Wait for my update very soon. – mathfux Aug 17 '20 at 09:11
  • Thank you @mathfux for your clues. I have solved it. – Rinku Aug 19 '20 at 05:54