In this video we’ll learn how to create File Dialog Boxes using Object Oriented Programming in Tkinter and Python.

File Dialog boxes allow us to select files to open in our Tkinter app.

We’ll build an app that opens a text file, reads the file, and renders the text onto a Text Widget.

Python Code: class_filedialog.py
(Github Code)

from tkinter import *
from tkinter import filedialog

class App(Tk):
	def __init__(self):
		super().__init__()

		# Title, icon, size
		self.title("Tkinter.com - OOP File Dialog")
		self.iconbitmap('images/codemy.ico')
		self.geometry('700x450')

		# Create Widgets
		self.my_text = Text(self, width=80, height=20)
		self.my_text.pack(pady=20)

		self.my_button = Button(self, text="Open File", command=self.file)
		self.my_button.pack(pady=20)



	# Create Popup Function
	def file(self):
		self.my_file = filedialog.askopenfilename(initialdir="", 
			title="Select a File",
			filetypes=(("txt files", "*.txt"), ("All Files", "*.*")))
		
		# Check to make sure user selected a file
		if self.my_file:
			# Open and read the file
			get_contents = open(self.my_file, "r")
			self.my_text.insert(END, get_contents.read())


# Define and instantiate our app
app = App()
app.mainloop()

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of the first dot com boom. After that he developed the award-winning Submission-Spider search engine submission software that's been used by over 3 million individuals, businesses, and governments in over 42 countries. He's written several Amazon #1 best selling books on coding, and runs a popular Youtube coding channel.

View all posts

Add comment

Your email address will not be published. Required fields are marked *

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of...