1

Python 3.10 (OS Windows 10, 64 bit)

Hi,

I compiled my Python tkinter code. When I run the *.exe twice there are two tkinter main windows (the same as when I'd run the windows notepad.exe twice).

But I want to prevent the tkinter .exe can be started twice. Can I do something so that tkinter can be started only one time no matter whether I click tkinter.exe on the windows desktop a dozen times .

Werner925
  • 39
  • 3
  • Do you have your code in a `main()` function? Do you care for cross platform compatibility? – Thingamabobs Jan 03 '22 at 10:10
  • [Check this answer](https://stackoverflow.com/questions/380870/make-sure-only-a-single-instance-of-a-program-is-running/54746426#54746426) – Samuel Kazeem Jan 03 '22 at 10:48
  • I mean at least one is is to have a file and when the program starts it checks that file, if nothing is there, it starts and writes to the file something, if something is there (the text that would be written if there was nothing), then it doesn't start, it immediately just exits and when you close the window (protocol 'WM_DELETE_WINDOW'), it clears that file – Matiiss Jan 03 '22 at 11:50
  • @Thingamabobs it just has to work in windows (not in other platforms) – Werner925 Jan 03 '22 at 12:23
  • 1
    @SamuelKazeem Thanks, your answer works for windows10: import win32event import win32api import sys from winerror import ERROR_ALREADY_EXISTS mutex = win32event.CreateMutex(None, False, 'name') last_error = win32api.GetLastError() if last_error == ERROR_ALREADY_EXISTS: sys.exit(0) – Werner925 Jan 03 '22 at 12:56

1 Answers1

0

@SamuelKazeem -Thanks. Your answer works for Windows10 :

import win32event
import win32api
import sys
from winerror import ERROR_ALREADY_EXISTS
mutex = win32event.CreateMutex(None, False, 'name')
last_error = win32api.GetLastError()
if last_error == ERROR_ALREADY_EXISTS:
   sys.exit(0)

import tkinter as tk
win=tk.Tk()
txt2=tk.Text(win, height=12, width=50)
win.title('python')
txt2.pack()
win.mainloop()
Werner925
  • 39
  • 3