In order to create buttons in a Tkinter application, we can use the Button widget. Buttons can be used to process the execution of an event in the runtime of an application. We can create a button by defining the Button(parent, text, **options) constructor.
Let us suppose we want to create a Browse Button which when clicked, will ask the user to select a file from the system explorer. To create a dialog box for selecting a file, we can use filedialog package in tkinter library. We can import the filedialog in the notebook using the following command,
from tkinter import filedialog
Once the package is imported in the program, we can use it to create a dialog box for opening and selecting all the Python files and it will return the number of characters present in that particular file.
# Import the required Libraries from tkinter import * from tkinter import ttk, filedialog from tkinter.filedialog import askopenfile # Create an instance of tkinter frame win = Tk() # Set the geometry of tkinter frame win.geometry("700x350") def open_file(): file = filedialog.askopenfile(mode='r', filetypes=[('Python Files', '*.py')]) if file: content = file.read() file.close() print("%d characters in this file" % len(content)) # Add a Label widget label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13')) label.pack(pady=10) # Create a Button ttk.Button(win, text="Browse", command=open_file).pack(pady=20) win.mainloop()
Now, run the above code to browse and select the files from the system explorer.