Home > Software engineering >  tkinter askopenfilename() function can't be used multiple times
tkinter askopenfilename() function can't be used multiple times

Time:11-28

I'm trying to run this function as long as entry is 1 or 2. but after the first valid input (1 or 2) the second one doesn't do anything and seems to get stuck in the loop

(the function prints the chosen file name the input number)

from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # there's no need to open the full GUI

def my_filebrowser(command):
    filename = askopenfilename()
    print(filename, command)

while True:

    command = int(input('enter command: '))

    if command == 1:
        my_filebrowser(command)

    elif command == 2:
        my_filebrowser(command)

    else:
        break

how should I change the code in order to use the tkinter file browser (askopenfilename() function) multiple times?

CodePudding user response:

You could simply create and destroy the root window to achive that, but it isnt a high performance approach.

from tkinter import Tk
from tkinter.filedialog import askopenfilename


def my_filebrowser(command):
    root = Tk(); root.withdraw()
    filename = askopenfilename()
    print(filename, command)
    root.destroy()

while True:

    command = int(input('enter command: '))

    if command == 1:
        my_filebrowser(command)

    elif command == 2:
        my_filebrowser(command)

    else:
        break

You can modify this code to have the filedialog in the front and in the middle of the screen. I also added alpha for transparency that you dosent even notice what happens:

def my_filebrowser(command):
    root = Tk(); root.attributes('-alpha',0.01)
    root.attributes('-topmost',True)
    root.tk.eval(f'tk::PlaceWindow {root._w} center')
    root.withdraw()
    filename = askopenfilename()
    root.destroy()
    print(filename, command)  
  • Related