How to automaticlly close or hide a tkinter window and be able to make it appear on conditions?

Viewed 21

I'm trying to make a more user friendly screen crosshair for games like Apex Legends,because exsisted ones can't atuomaticlly go disappear when you returns to desktop,minimize the game window or switch to a browers while the game is still running with borderless window mode.I chose Python to make it because I'm most familiar with it(just started to learn coding recently).You can see my codes and error information below:

import time
from tkinter import *

class CrosshairWindow:
    def __init__(self):
        self.root = Toplevel()
        self.root.attributes(
            '-transparentcolor', '#ffffff',
            '-topmost', '1'
        )
        self.root.overrideredirect(1)

        self.screen_width = self.root.winfo_screenwidth()
        self.screen_height = self.root.winfo_screenheight()

    def start(self):
        image = PhotoImage(file='crosshair.png')

        canvas = Canvas(self.root, width=image.width(), height=image.height(), highlightthickness=0)
        canvas.pack(fill='both')
        canvas.create_image(0, 0, anchor=NW, image=image)

        self.root.geometry(f'%sx%s+%s+%s' % (
            image.width(),  # width
            image.height(),  # height
            round(self.screen_width/2 - image.width()/2),  # x offset
            round(self.screen_height/2 - image.height()/2),  # y offset
        ))

        self.root.lift()
        self.root.mainloop()

if __name__ == '__main__':
    import win32gui as w
    print('Started!')
    while(True):
        title = w.GetWindowText(w.GetForegroundWindow())
        print(title)
        cw = CrosshairWindow()
        while 1:
            time.sleep(1)
            print(title)
            title = w.GetWindowText(w.GetForegroundWindow())
            if title == "Apex Legends":
                key = True
            else:
                key = False
            print(title)
            if key==True:
                cw.start()
            else:
                cw.root.destroy()
C:\ProgramData\Anaconda3\python.exe "C:/Users/Hosisora_Ling/Documents/Tencent Files/2374416274/FileRecv/crosshair.py"
Started!
新建文件夹 – C:\Users\Hosisora_Ling\Documents\Tencent Files\2374416274\FileRecv\crosshair.py
Traceback (most recent call last):
  File "C:\Users\Hosisora_Ling\Documents\Tencent Files\2374416274\FileRecv\crosshair.py", line 41, in <module>
    cw.start(0)
  File "C:\Users\Hosisora_Ling\Documents\Tencent Files\2374416274\FileRecv\crosshair.py", line 33, in start
    self.root.lift()
  File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1026, in tkraise
    self.tk.call('raise', self._w, aboveThis)
_tkinter.TclError: can't invoke "raise" command: application has been destroyed

进程已结束,退出代码1#program ended with exit code 1

Please help point out the mistakes or a posible way to achieve my goal!

0 Answers
Related