- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Gini Index for Decision Trees
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Brand Manager Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Search Engine Optimization
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
Python Tkinter Projects [Step-by-Step Explanation]
Updated on 08 January, 2024
10.44K+ views
• 14 min read
Table of Contents
Learning about GUI in Python can be quite challenging. Don’t worry because we have got your back! In this article, we’ve shared a Tkinter tutorial so you can work on Python GUI projects efficiently. After completing this tutorial, you’d be familiar with the building blocks for creating Python Tkinter projects. If you want to gain more expertise in python, checkout our data science programs.
We’ve also shared the code for every step. However, we recommend that you copy and paste it only when you understand how it works. Otherwise, it wouldn’t be of much use.
What is Tkinter?
Tkinter is a package for Python to use the Tk GUI toolkit. You can use Tkinter for creating GUI programs through Python. While Tkinter is capable of producing many programs, you might need to use modules for advanced implementations. You should be familiar with the basics of Tkinter before working on Python Tkinter projects:
Tkinter Widgets
Tkinter widgets are basically controls such as buttons, text boxes, and labels, that are used in GUI applications. There are as many as 15 types of Tkinter widgets, namely, canvas, label, frame, menu, menubutton, and message, among others.
A Hello World Program in Tkinter
Here’s an example of a hello world program in Tkinter:
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there[“text”] = “Hello World\n(click me)”
self.hi_there[“command”] = self.say_hi
self.hi_there.pack(side=”top”)
self.quit = tk.Button(self, text=”QUIT”, fg=”red”,
command=self.master.destroy)
self.quit.pack(side=”bottom”)
def say_hi(self):
print(“hi there, everyone!”)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
Geometry Managers in Tkinter
Another main concept you should know about while working on Python Tkinter projects is geometry managers. Without using a geometry manager, your widgets wouldn’t appear on the screen. There are primarily three ways you can add a geometry manager:
Grid
It adds a grid to the parent and allows it to show widgets accordingly. The grid has rows and columns for measuring the length and height of its widgets.
Pack
This method tells the widget to pack itself within the parent. It only adds the widget to a list of children widgets for the parent. In simple terms, it adds them to a block before it places them in a parent widget.
Place
This method places widgets in a specific location according to the parent widget.
In our tutorial below, we have used the pack manager for handling the position of our widgets. That’s why it’d be best if you’re familiar with these concepts. It would help you to understand the working of our project better.
Checkout: 42 Exciting Python Project Ideas & Topics for Beginners
Building a GUI in Python (Tkinter Tutorial)
Step#1: Importing the Module
To begin working on the application, we first have to import the necessary module. You can do so by importing the module in your namespace. It would allow you to use the constants and classes by their names instead of qualifying them. This means you can use “Label” by using its name instead of qualifying it as “TkinterLabel.” It would make things relatively easy, and you can save a lot of time as qualifying every class and constant can be very cumbersome. Use the following code to import the module:
>>> from Tkinter import *
If Python is not linked to Tk (or Tcl) in your system or if you don’t have Tk (or Tcl) installed in your system, you would see an error message in this section. To fix this issue, you would need your system’s administrator for access. Make sure that you solve this problem by doing the same.
On the other hand, if you don’t see any error messages in these sections, you can move onto the next step to create a window:
>>> win = Tk()
We’ve assigned our window the variable “win.” After implementing the code above, you would get to see a small window on the screen. Its title bar should show “tk” written in it.
This means you’ve completed this step successfully and can now start building GUI in Python.
Read our popular Data Science Articles
upGrad’s Exclusive Data Science Webinar for you –
How to Build Digital & Data Mindset
Explore our Popular Data Science Courses
Step#2: Adding Buttons
Now that we have our Tkinter running, we can add buttons to our program. Buttons are the simplest section of any GUI program, so we’ll start with them:
>>> b1 = Button(win, text=”One”)
>>> b2 = Button(win, text=”Two”)
The window we created in the last section is the parent for the buttons we made now. As you’ll work on more Python Tkinter projects, you’ll find that frames can also act as parents for other classes. Now, when you implement this code, you would notice a strange occurrence – The buttons don’t appear in the window!
That’s because we need to add a grid and a pack to our program. They are called geometry managers, and we’ve discussed them earlier in this article. We’ll add the pack manager in our next section:
Step#3: Implementing the Pack Manager
We’ll use the pack method to add our buttons to the parent widget. With the pack manager, you can tell which side of the parent widget you want your child widget to be packed against. You can use TOP, RIGHT, BOTTOM, LEFT as your functions. The program selects TOP as default if you don’t specify a side. Let’s add the pack manager first:
>>> b1.pack()
>>> b2.pack()
When you add the first button (first line of the code), you will notice that your window shrinks to the button’s size. Similarly, when you add the second button (second line of the code), the window expands according to that button’s size. The window has placed the buttons in vertical order because we didn’t specify which side they should be packed against. Let’s pack them on the left by using the code below:
>>> b2.pack(side=LEFT)
>>> b1.pack(side=LEFT)
Note that we use the pack manager mostly when we have to place our widgets in these two orders (horizontal and vertical) only. For other types of widget placements, we use the grid method or the place method. You can add some space between the buttons and the window using the ‘padx’ or ‘pady’ functions. The ‘padx’ function adds padding to the X-axis (left and right) of the widget, and the ‘pady’ function adds padding to the Y-axis (top and bottom) of the device.
>>> b1.pack(side=LEFT, padx=10)
>>> b2.pack(side=LEFT, padx=10)
We recommend experimenting with the padding of the widgets. It would help you in understanding the different ways you can modify the placement of widgets. Padding is a challenging concept to master, so it would be best to try it out before you move onto the next section.
Also, Check out all trending Python tutorial concepts in 2024.
Step#4: The Grid Manager
Another popular geometry manager in Tkinter is the grid manager. As we’ve discussed earlier in our article, the grid manager allows you to divide the parent into rows and columns. You can place the child widgets in the cells of the parent’s grid. You can modify the width and length of every column and row according to your requirements. Not every column has to be of the same width. Similarly, every row doesn’t need to have the same height. So, the grid manager gives you more creative liberty in terms of editing your widgets’ appearance and placement.
We’ll create a new window with the same buttons we created before to test out the grid manager. However, we’ll add the buttons in a 2×2 grid:
>>> win = Tk()
>>> b1 = Button(win, text=”One”)
>>> b2 = Button(win,text=”Two”)
>>> b1.grid(row=0, column=0)
>>> b2.grid(row=1, column=1)
You’d notice that our program has left some cells empty. That’s because we didn’t add anything to row 0, column 1 (or row 1 and column 0). We will try a new widget to see something interesting:
>>> l = Label(win, text=”This is a label”)
>>> l.grid(row=1, column=0)
Once you add the above code, you notice that the second button shifts to the right to accommodate the text. It would be best to try out the grid manager with multiple widgets to see how it functions.
Must Read: Django Developer Salary in India
Top Data Science Skills to Learn
Step#5: Improving the Layout
In this section we’ll try a new widget called frame. A frame is only for containing other widgets. You can pack multiple widgets into a frame or use a grid to place them in the same. You can also pack different frames into a single frame. This feature allows you to create advanced layouts for your GUI program. For example, we’ll add three buttons to a frame in a row. Add the buttons horizontally and then pack the label vertically with the frame:
>>> win = Tk()
>>> f = Frame(win)
>>> b1 = Button(f, “One”)
>>> b2 = Button(f, “Two”)
>>> b3 = Button(f, “Three”)
>>> b1.pack(side=LEFT)
>>> b2.pack(side=LEFT)
>>> b3.pack(side=LEFT)
>>> l = Label(win,”This label is over all buttons”)
>>> l.pack()
>>> f.pack()
As we have discussed earlier in the article, you can also use the place method as the geometry manager. The place method allows you to put widgets in a specific location within a window or a frame. However, we don’t recommend using the place method frequently because it restricts the program’s responsiveness.
With the grid function, you can use the ‘sticky’ parameter that allows you to use map coordinates (S, N, W, SW, NE, etc.) for specifying widget placements. Before we move onto the next section, make sure that you understand the functions we’ve discussed yet. Test out the grid, and the frame functions together to see how you can use it in other Python GUI projects.
Step#6: Making the Buttons Useful
If you’d click the buttons we’ve created so far, you must have noticed that they are unresponsive (they don’t do anything). They depress when you click and highlight when you hover above them, but they don’t perform any functions. To make our buttons perform specific functions, we’ll have to use the ‘configure’ function.
We can pass any keyword argument to a widget’s ‘configure’ method to pass it while creating it. Here’s an example:
>>> b1.configure(text=”Uno”)
The ‘command’ parameter ties the buttons to callback functions when you create them or add ‘configure’ to them. To understand how it works, we’ll create a function that prints out a message:
>>> def but1():
… print(“Button one was pushed”)
…
>>> b1.configure(command=but1)
So when you’d click the respective button, it would print a message.
Step#7: Adding Entry Widgets
Entry widgets allow users to enter text into the program. However, we would have to make the entry widget functional as we did with the buttons. An entry widget has to retrieve (and set) text. For the entry widget to perform this function, you’d have to use the Tkinter object ‘StringVar.’ The ‘StringVar’ object holds the text in the form of a string and makes it readable through get.
We’ll create a new window to test our entry widgets:
>>> win = Tk()
>>> v = StringVar()
>>> e = Entry(win,textvariable=v)
>>> e.pack()
Let’s now add “this is a test” as the entry and retrieve the same through StringVar:
>>> v.get()
“this is a test”
You can now set the text into StringVar and make it appear in the widget:
>>> v.set(“this is set from the program”)
Additional Widget: The Listbox Widget
Apart from the entry widget, we can add a listbox widget. A listbox widget lets the user choose an item from a menu. We’ll create a new window to try out the listbox widget:
>>> win = Tk()
>>> lb = Listbox(win, height=3)
>>> lb.pack()
>>> lb.insert(END, “first entry”)
>>> lb.insert(END, “second entry”)
>>> lb.insert(END, “third entry”)
>>> lb.insert(END, “fourth entry”)
You can insert items at the beginning, the middle, and the end of the list. You can delete them too. If there are too many items on the list, you can add a scrollbar:
>>> sb = Scrollbar(win, orient=VERTICAL)
>>> sb.pack(side=LEFT, fill=Y)
To make our scrollbar functional we’ll have to use call back functions:
>>> sb.configure(command=lb.yview)
>>> lb.configure(yscrollcommand=sb.set)
The curselection method returns an item to you when you select it in the list box. It will return an empty tuple if you don’t choose any items.
Step#8: Final Steps
We’ll use all the stuff we learned in our Tkinter tutorial to create a phone list editor:
Total Code
#!/usr/bin/env python3
from tkinter import *
from phones import *
def which_selected():
print(“At {0}”.format(select.curselection()))
return int(select.curselection()[0])
def add_entry():
phonelist.append([fnamevar.get(), lnamevar.get(), phonevar.get()])
set_select()
def update_entry():
phonelist[which_selected()] = [fnamevar.get(),
lnamevar.get(),
phonevar.get()]
def delete_entry():
del phonelist[which_selected()]
set_select()
def load_entry():
fname, lname, phone = phonelist[which_selected()]
fnamevar.set(fname)
lnamevar.set(lname)
phonevar.set(phone)
def make_window():
global fnamevar, lnamevar, phonevar, select
win = Tk()
frame1 = Frame(win)
frame1.pack()
Label(frame1, text=”First Name”).grid(row=0, column=0, sticky=W)
fnamevar = StringVar()
fname = Entry(frame1, textvariable=fnamevar)
fname.grid(row=0, column=1, sticky=W)
Label(frame1, text=”Last Name”).grid(row=1, column=0, sticky=W)
lnamevar = StringVar()
lname = Entry(frame1, textvariable=lnamevar)
lname.grid(row=1, column=1, sticky=W)
Label(frame1, text=”Phone”).grid(row=2, column=0, sticky=W)
phonevar = StringVar()
phone = Entry(frame1, textvariable=phonevar)
phone.grid(row=2, column=1, sticky=W)
frame2 = Frame(win) # Row of buttons
frame2.pack()
b1 = Button(frame2, text=” Add “, command=add_entry)
b2 = Button(frame2, text=”Update”, command=update_entry)
b3 = Button(frame2, text=”Delete”, command=delete_entry)
b4 = Button(frame2, text=”Load “, command=load_entry)
b5 = Button(frame2, text=”Refresh”, command=set_select)
b1.pack(side=LEFT)
b2.pack(side=LEFT)
b3.pack(side=LEFT)
b4.pack(side=LEFT)
b5.pack(side=LEFT)
frame3 = Frame(win) # select of names
frame3.pack()
scroll = Scrollbar(frame3, orient=VERTICAL)
select = Listbox(frame3, yscrollcommand=scroll.set, height=6)
scroll.config(command=select.yview)
scroll.pack(side=RIGHT, fill=Y)
select.pack(side=LEFT, fill=BOTH, expand=1)
return win
def set_select():
phonelist.sort(key=lambda record: record[1])
select.delete(0, END)
for fname, lname, phone in phonelist:
select.insert(END, “{0}, {1}”.format(lname, fname))
win = make_window()
set_select()
win.mainloop()
Here is the phone list:
phonelist = [[‘Chris’, ‘Meyers’, ‘241-343-4349’],
[‘Robert’, ‘Smith’, ‘202-689-1234’],
[‘Janet’, ‘Jones’, ‘609-483-5432’],
[‘Ralph’, ‘Barnhart’, ‘215-683-2341’],
[‘Eric’, ‘Nelson’, ‘571-485-2689’],
[‘Ford’, ‘Prefect’, ‘703-987-6543’],
[‘Mary’, ‘Zigler’, ‘812-567-8901’],
[‘Bob’, ‘Smith’, ‘856-689-1234’]]
The program we shared here is an example. You can create your program with the functions we discussed in this Tkinter tutorial. The above program lacks several functionalities, such as it doesn’t have the option to save any changes. You can add the save function by yourself by creating a button that can perform this task.
Must Read: Markov Chain in Python Tutorial
Advantages of Tkinter Module In Python
Now that you have a basic understanding of what exactly Python Tkinter refers to, and how it operates, let’s take a look at some of the basic advantages of the Tkinter module in Python that are mentioned below.
- When compared with other GUI toolkits, Tkinter is much easier and faster to use.
- You no longer need to download anything extra, since Tkinter is already included in Python.
- Tkinter has a simple syntax, as well as three geometry managers, namely grid, place, and pack.
- Last but not least, Python Tkinter is also extremely easy to understand, and can be mastered quite easily.
What is Python GUI Programming?
GUI, also known as Graphical User Interfaces, are computer programs that enable users to make use of visuals in order to interact with underlying systems. A basic example of the same might include our mobile phones, which are equipped with such GUIs that help us to interact with various functionalities through tap, touch, or display. Similarly, Python GUI is a graphical user interface that is written in this programming language. As we all know, Python, by far, is considered to be one the most popular programming languages due to its several benefits, such as easy readability, and beginner friendliness, among others. Furthermore, this programming language is also equipped with various frameworks that make it great for developing a graphical user interface.
Python GUI Programming Use Cases
Mobile Applications- Instagram, Reddit, and Pinterest are some of the best examples of mobile applications that make use of Python GUI.
Games- Several gaming applications, such as Flappy Bird or Mount & Blade, also make use of Python GUI in order to provide a better user experience, such as flashy graphics, and rewarding interactivity.
Human-Machine Interfaces- Last but not least, human-machine interfaces are present across various industries. Human-machine interfaces, also known as HMI, are basically graphic user interfaces that are responsible for providing an overview of industrial monitoring and control systems. Furthermore, this also includes providing appropriate solutions in case of any anomalies in the operating system. Python makes the development of these industrial applications much easier and at a reduced cost, which is one of the most important requirements of all businesses.
Learn More About Python and Python GUI Projects
Working on Python Tkinter projects can be pretty fun if you know what you’re doing. They are also a great way to understand your strong (and the weak) points. You can learn more about Python; we recommend heading to our blog. Here are some resources for further reading:
What are your thoughts on this project? Have you worked on other Python Tkinter projects? Let us know.
If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.
Frequently Asked Questions (FAQs)
1. Is Python suitable for creating graphical user interfaces?
Python has a number of graphical user interface frameworks, ranging from Tkinter to a number of other cross-platform solutions, as well as platform-specific bindings. Creating graphical user interfaces is quick and easy when Python is combined with Tkinter. Python is ideal for GUI creation because it has a lot of built-in widgets, it generates windows quickly, has strong event handling techniques, and has rudimentary drawing capabilities.
2. Tkinter or KIVY: which is better to use?
Kivy is a free and open-source Python framework for creating or designing unique but appealing user interface programmes. If you're a python developer who enjoys creating apps, KIVY is an excellent choice for creating more dynamic applications. Tkinter is the most widely used Python interface for developing GUI applications quickly and easily. If you're new to Python and want to learn how to create computer interfaces, start with Tkinter and learn the fundamentals.
3. What are some of the drawbacks of using Tkinter Python?
Advanced widgets are not included in Tkinter. It doesn’t have a tool like Qt Designer for Tkinter. It doesn’t have a dependable user interface. Tkinter can be difficult to debug at times. It lacks a native appearance and feel. Tkinter can be useful for creating simple and quick GUIs for Python scripts, but for more complex programming output, almost all programmers prefer the PyQt capabilities.