有时候我们需要程序只运行一个实例,在windows平台下我们可以很简单的用mutex实现这个目的。
  在开始时,程序创建了一个命名的mutex,这个mutex可以被其他进程检测到。 这样如果程序已经启动,再次运行时的进程就可以检测到程序已运行,从而不会继续运行。

from tkinter import *
import win32event, pywintypes, win32api
from winerror import ERROR_ALREADY_EXISTS
class MyFrm(Frame):
    def __init__(self, master):
        self.root=master
        self.screen_width = self.root.winfo_screenwidth()#获得屏幕宽度
        self.screen_height = self.root.winfo_screenheight()  #获得屏幕高度
        #self.root.resizable(False, False)#让高宽都固定
        self.root.update_idletasks()#刷新GUI
        self.root.withdraw() #暂时不显示窗口来移动位置
        self.root.geometry('%dx%d+%d+%d' % (self.root.winfo_width(), self.root.winfo_height() ,(self.screen_width - self.root.winfo_width()) / 2,(self.screen_height - self.root.winfo_height()) / 2))  # center window on desktop
        self.root.deiconify()
        Label(self.root,text='程序运行中...').pack(fill=BOTH,expand=YES)

if __name__=='__main__':
    mutexname = "DEMO"#互斥体命名
    mutex = win32event.CreateMutex(None, FALSE, mutexname)
    if (win32api.GetLastError() == ERROR_ALREADY_EXISTS):
        print('程序已启动')
        exit(0)
    root=Tk()
    MyFrm(root)
    root.mainloop()

相关文章:

  • 2022-01-20
  • 2021-08-08
  • 2022-12-23
  • 2021-10-22
  • 2021-10-06
  • 2021-06-06
  • 2021-06-29
猜你喜欢
  • 2021-09-25
  • 2021-08-26
  • 2021-08-29
  • 2022-12-23
  • 2021-08-05
  • 2022-12-23
  • 2021-06-07
相关资源
相似解决方案