In this video we’ll learn how to use Classes and Object Oriented Python to build our own widgets and components.

Tkinter is great, but it becomes super powerful when you can create your own components.

And it’s actually pretty easy! Customize your own widgets and components and then call them any time you want!

Python Code: custom_widget.py
(Github Code)

from tkinter import *

root = Tk()
root.title('Tkinter.com - Custom Widgets/Components')
root.iconbitmap('images/codemy.ico')
root.geometry('700x450')

class My_widget(Frame):
	def __init__(self, parent, label_text, button_text, button_name):
		super().__init__(master = parent)

		# Set up our grid stuff
		self.rowconfigure(0, weight=1)
		self.columnconfigure((0,1), weight=1, uniform='z')

		# Create our widgets
		Label(self, text=label_text, font=("Helvetica", 18)).grid(row=0, column=0, sticky="nsew")
		Button(self, text=button_text, command=lambda: self.change(button_name)).grid(row=0, column=1, sticky="nsew")

		self.pack(expand=True, fill="both", padx=10, pady=10)

	def change(self, name):
		if name == "my_button1":
			root.title("Button 1!")
		elif name == "my_button2":
			root.title("Button 2!")
		elif name == "my_button3":
			root.title("Button 3!")
		else:
			root.title("Something else!")


My_widget(root, "Text 1", "Button 1", "my_button1")
My_widget(root, "Text 2", "Button 2", "my_button2")
My_widget(root, "Text 3", "Button 3", "my_button3")
My_widget(root, "Text 4", "Button 4", "my_button4")


root.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...