0

how to know that user cliked on "X" button on top right corner of tkinter window and closed ( destroyed ) it? i want to use the result of this to destroy another while loop.\

edit : i reviewed the suggested question but no , it does not answer my question because it's about how to close a tkinter window

edit : the code:

import socket
from tkinter import *
import threading

win = Tk()
win.geometry("300x300")
win.resizable(False,False)


def disc() :
    s = socket.socket()
    ip = "0.0.0.0"
    port = 9999
    s.bind((ip,port))
    s.listen()
    print ('please wait...')
    c , addr =s.accept()
     print ('someone has joined!')


    while True :
        msg = input('your message : ' )
        c.send(msg.encode('utf8'))
        print (c.recv(1024).decode())

lbl_1 = Label(win,text="mychat",bg="light blue")
lbl_1.place(x=130,y=20)

word_1 = "hello"
word_2 = "hello2"

print(socket.gethostbyname(socket.gethostname()))

txt_1 = Text(win)
txt_1.pack()
txt_1.insert(END, word_1)
txt_1.insert(END, word_2)

connection = threading.Thread(target=disc).start()

win.mainloop()

it's a messenger. here even after i close the window , the process remains but want to destroy the disc() process too.

Parsa Ad
  • 91
  • 6
  • May you please add a sample code of what you're trying to do? is the "another while loop" corresponds to a child window? – CodeCop Feb 10 '23 at 18:08
  • The linked question does answer your question – Matiiss Feb 10 '23 at 18:17
  • Are you wanting to know _if_ a window was destroyed, or do you need to capture the moment it is destroyed so that you can call other functions? – Bryan Oakley Feb 10 '23 at 18:19
  • [This answer](https://stackoverflow.com/a/111160/7432) shows how to run additional code when the user destroys the window by clicking on the "x" in the window titlebar. – Bryan Oakley Feb 10 '23 at 18:21
  • @BryanOakley no , i want to know if a window is destroyed. and because of that , the question you guys link me , is not answering my question. – Parsa Ad Feb 10 '23 at 18:24
  • Using a protocol handler *is* the way you know the window is destroyed. You know it happened because the callback bound to the protocol handler is called. The linked answers *do* answer your question. How you set up the callback is entirely up to you. – JRiggles Feb 10 '23 at 18:42
  • @JRiggles: I think what is being asked is, how to check _inside the loop_ whether the root window has been destroyed. – Bryan Oakley Feb 10 '23 at 19:08

1 Answers1

2

If you want to continually check whether a window has been destroyed or not, you need a reference to the window. You can then call the winfo_exists method to determine if the window exists or not.

while True :
    ...
    if not win.winfo_exists():
        # window no longer exists; break out of loop
        break
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685