- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating a Browse Button with Tkinter
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.
- Creating a button in tkinter in Python
- Tkinter button commands with lambda in Python
- Creating a Dropdown Menu using Tkinter
- Creating a LabelFrame inside a Tkinter Canvas
- Creating Clickable Tkinter labels
- Call a Function with a Button or a Key in Tkinter
- How to stop a loop with a stop button in Tkinter?
- Creating a Frameless window in Python Tkinter
- Creating a Transparent window in Python Tkinter
- Creating a prompt dialog box using Tkinter?
- Creating a popup message box with an Entry field in tkinter
- Creating a transparent background in a Tkinter window
- Creating a table look-a-like using Tkinter
- Creating Tkinter full-screen application
- Add image on a Python Tkinter button