[Tutor] How to close a Tkinter window from a different thread?

boB Stepp robertvstepp at gmail.com
Tue Apr 21 04:34:39 CEST 2015


On Mon, Apr 20, 2015 at 2:10 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 20/04/15 04:34, boB Stepp wrote:
>
>> So, how do I:
>> 1) Check for the existence of an already open window from a previous
>> running of the script?
>> 2) If such a window exists, how do I close it from the new script
>> execution? And, then, of course generate a new instance of the
>> information window.
>
>
> I would suggest forgetting about windows and think about
> the processes that create them. Use the OS tools (via
> the os module) to see if the first process is still running.
> If so kill the process - which will in turn kill the window.
>
> You can find the process based on its name or based on
> its PID which you could store in a file somewhere
> (like in /tmp?)

I'm currently at home and cannot access Solaris, but I believe that
the following will do what I want:

import os
import signal
from tkinter import *

def kill():
    os.kill(pid, signal.SIGKILL)

root = Tk()
pid = os.getpid()

btn = Button(root, text='Kill me!!!', command=kill)
btn.pack()
root.mainloop()

The process id would have to be stored persistently to do the real
deal, of course, as Alan suggested. I cannot make this example work in
Windows. As far as I can tell, signal.SIGKILL won't work with Windows.
If I replace it with 9, then it does work. If I have understood what I
have read to date, using signal.SIGKILL is preferable to using 9.

Some questions:

1) Is the placement of "pid = os.getpid()" critical? My thinking is
that I want to capture the pid of the root window, store it, and then
use it if I need to kill the root and any children it has in my actual
GUI display. If, say, I placed it immediately before
"root.mainloop()", would it do what I want? Of course, I plan to
experiment with this at work tomorrow. I'll also continue to play
around with it in Windows.

2) The other possibility was to use "os.getppid" and, I suppose,
"os.kill(ppid, signal.SIGKILL)". Would this be preferable? Or will
wreak some sort of havoc?

Thanks!
boB


More information about the Tutor mailing list