Tkinter opens the Filedialog twice to take the File

Tags: , ,



I have two functions CheckOs and _get_keyfile as below:
1:CheckOs(without considering Mac)

def CheckOs():
    if os.name == 'nt':
        return "Windows"
    return "Linux"

2:_get_keyfile

def _get_keyfile(stdscr):
    keyfile = Tk()
    keyfile.withdraw()
    if CheckOs() == "Windows":
        keyfile.KeyfileName = filedialog.askopenfilename(initialdir="/", title="Selecta Key File",filetypes=(("Anfu Keyfiles", "*.anky"),))
    #if not windows then linux,IGNOREEEEEEEEE MAC
    keyfile.KeyfileName = filedialog.askopenfilename(initialdir="/home", title="Select a Key File",filetypes=(("Anfu Keyfiles", "*.anky"),))
    keyfile.destroy()
    return keyfile.KeyfileName

the problem is when ever _get_keyfile Function is executed it opens the File Dialog to select the file but opens again after I select the file and the file is selected after the second time. The problem only persists on Windows on Linux its working fine.
I want to know if I am doing something wrong or is that a bug in Tk .Any help Appreciated

Answer

In the _get_keyfile function change the function to include a else after the if to avoid opening dialog box. If it’s not a Linux OS

def _get_keyfile(stdscr):
    keyfile = Tk()
    keyfile.withdraw()
    if CheckOs() == "Windows":
        keyfile.KeyfileName = filedialog.askopenfilename(initialdir="/", title="Select a Key File",filetypes=(("Anfu Keyfiles", "*.anky"),))
   
    else:
        keyfile.KeyfileName = filedialog.askopenfilename(initialdir="/home", title="Select a Key File",filetypes=(("Anfu Keyfiles", "*.anky"),))

    keyfile.destroy()
    return keyfile.KeyfileName
    

As a result the dialog box will only pop-up one time
Happy Coding!



Source: stackoverflow