Home > Software design >  How to check if a tkinter app has been opened before? (Tkinter python)
How to check if a tkinter app has been opened before? (Tkinter python)

Time:08-25

I'm making an app in tkinter that has a start up/welcome screen. How could I check if the app has been opened before, so that the next time the person opens the app/runs the script, they don't get the welcome screen anymore. Also, I'd like for a reset option that would trigger the welcome screen again. I know this is achievable, but I just don't know how. Thanks for your time!

CodePudding user response:

This is just a quick idea as there are many ways you could get creative with this. I love try and except for this type of behavior. It is a great tool for something like this IMO. Hopefully this gives you an idea of what I meant.

*UPDATED to add suggestions from comments

from pathlib import Path
import os
import tkinter as tk


# consider changing directory to avoid permission issues as stated in comments based on OS
file = Path("File.txt")

try:
    with open(file, "r"):  # try to open the file
        print("Not first Launch, No welcome screen")
except FileNotFoundError:
    with open(file, "x"):  # "x" will create the file as pointed out in comments
        print("First time launch, file was created, welcome screen activated")


def reset():
    try:
        os.remove(file) # remove the file if it is there
        print("Reset perfomed, file deleted")
    except FileNotFoundError:
        print("Program already reset")

        
root = tk.Tk()

reset_button = tk.Button(root, text="Reset", command=reset)
reset_button.pack()

root.mainloop() 
  • Related