How to give Tkinter file dialog focus?


Tkinter Python library can be used to create functional and featured applications. It has lots of packages and functions that are used for different functionalities. The filedialog package in tkinter gives access to interact with the file system in a local machine. Using filedialog, we can get access to any file from the system and use it to perform CRUD operation.

To give the focus to the file dialog, we can have a parent window that is associated with the dialog. If the main window is defined globally on the top, the associated widgets get focused automatically on the top of others.

Example

In this example, we have created a button that will open up a dialog box to select a file from the local system.

# Import the tkinter library
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the Tkinter window
win.geometry("700x350")

# Set the title of the window
win.title("File Explorer")

# Define the function to open the file dialog
def open_file():
   win.filename = filedialog.askopenfilename(title="Select the file", filetypes=(("jpg files", "*.jpg"), ("all files", "*.*")))]

# Create a Button widget
b1 = Button(win, text="Open", command=open_file)
b1.place(relx=.5, rely=.5, anchor=CENTER)
win.mainloop()

Output

Running the above code will display a window with a button.

Upon clicking the Button, it will show a dialog box from where the user can select a file from the local system.

Updated on: 07-Jun-2021

570 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements