0% found this document useful (0 votes)
237 views19 pages

Create GUI Apps with Python Tkinter

Uploaded by

stylishdeepak95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Topics covered

  • SQLite,
  • event-driven programming,
  • Menu widget,
  • pack method,
  • widgets,
  • Frame widget,
  • desktop applications,
  • Scrollbar widget,
  • Entry widget,
  • Canvas widget
0% found this document useful (0 votes)
237 views19 pages

Create GUI Apps with Python Tkinter

Uploaded by

stylishdeepak95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Topics covered

  • SQLite,
  • event-driven programming,
  • Menu widget,
  • pack method,
  • widgets,
  • Frame widget,
  • desktop applications,
  • Scrollbar widget,
  • Entry widget,
  • Canvas widget

Create First GUI Application using Python-Tkinter

We are now stepping into making applications with graphical elements, we will learn how to
make cool apps and focus more on its GUI(Graphical User Interface) using Tkinter.
What is Tkinter?
Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI
frameworks, but Tkinter is the only framework that’s built into the Python standard library.
Tkinter has several strengths; it’s cross-platform, so the same code works on Windows,
macOS, and Linux.
Tkinter is lightweight and relatively painless to use compared to other frameworks. This
makes it a compelling choice for building GUI applications in Python, especially for
applications where a modern shine is unnecessary, and the top priority is to build something
functional and cross-platform quickly.
Use Cases of Tkinter
1. Creating windows and dialog boxes: Tkinter can be used to create windows and dialog
boxes that allow users to interact with your program. These can be used to display
information, gather input, or present options to the user.
To create a window or dialog box, you can use the Tk() function to create a root window, and
then use functions like Label, Button, and Entry to add widgets to the window.
2. Building a GUI for a desktop application: Tkinter can be used to create the interface for
a desktop application, including buttons, menus, and other interactive elements.
To build a GUI for a desktop application, you can use functions like Menu, Checkbutton, and
RadioButton to create menus and interactive elements and use layout managers like pack and
grid to arrange the widgets on the window.
3. Adding a GUI to a command-line program: Tkinter can be used to add a GUI to a
command-line program, making it easier for users to interact with the program and input
arguments.
To add a GUI to a command-line program, you can use functions like Entry and Button to
create input fields and buttons, and use event handlers like command and bind to handle user
input.
4. Creating custom widgets: Tkinter includes a variety of built-in widgets, such as buttons,
labels, and text boxes, but it also allows you to create your own custom widgets.
To create a custom widget, you can define a class that inherits from the Widget class and
overrides its methods to define the behavior and appearance of the widget.
5. Prototyping a GUI: Tkinter can be used to quickly prototype a GUI, allowing you to test
and iterate on different design ideas before committing to a final implementation.
To prototype a GUI with Tkinter, you can use the Tk() function to create a root window, and
then use functions like Label, Button, and Entry to add widgets to the window and test
different layouts and design ideas.
Tkinter Alternatives
There are several libraries that are similar to Tkinter and can be used for creating graphical
user interfaces (GUIs) in Python. Some examples include:
1. PyQt: PyQt is a GUI library that allows you to create GUI applications using the Qt
framework. It is a comprehensive library with a large number of widgets and features.
2. wxPython: wxPython is a library that allows you to create GUI applications using the
wxWidgets framework. It includes a wide range of widgets in it’s GUI toolkit and is
cross-platform, meaning it can run on multiple operating systems.
3. PyGTK: PyGTK is a GUI library that allows you to create GUI applications using the
GTK+ framework. It is a cross-platform library with a wide range of widgets and
features.
4. Kivy: Kivy is a library that allows you to create GUI applications using a modern,
responsive design. It is particularly well-suited for building mobile apps and games.
5. PyForms: PyForms is a library that allows you to create GUI applications using a
simple, declarative syntax. It is designed to be easy to use and has a small footprint.
6. Pygame: PyForms is a library that is popular because you can develop video games
using it. It is a free, open source, and cross-platform wrapper for the Simple
DirectMedia Library (SDL). You can check Pygame Tutorial if you are interested in
video game development.
In summary, there are several libraries available for creating GUI applications in Python,
each with its own set of features and capabilities. Tkinter is a popular choice, but you may
want to consider other options depending on your specific needs and requirements.
To understand Tkinter better, we will create a simple GUI.
Getting Started with Tkinter
1. Import tkinter package and all of its modules.
2. Create a root window. Give the root window a title(using title()) and dimension(using
geometry()). All other widgets will be inside the root window.
3. Use mainloop() to call the endless loop of the window. If you forget to call this nothing
will appear to the user. The window will wait for any user interaction till we close it.
# Import Module
from tkinter import *

# create root window


root = Tk()

# root window title and dimension


[Link]("Welcome to GeekForGeeks")
# Set geometry (widthxheight)
[Link]('350x200')

# all widgets will be here


# Execute Tkinter
[Link]()
Output

Root Window
4. We’ll add a label using the Label Class and change its text configuration as desired. The
grid() function is a geometry manager which keeps the label in the desired location inside the
window. If no parameters are mentioned by default it will place it in the empty cell; that is 0,0
as that is the first location.
# Import Module
from tkinter import *

# create root window


root = Tk()

# root window title and dimension


[Link]("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
[Link]('350x200')

#adding a label to the root window


lbl = Label(root, text = "Are you a Geek?")
[Link]()

# Execute Tkinter
[Link]()
Output

Label inside root window


5. Now add a button to the root window. Changing the button configurations gives us a lot of
options. In this example we will make the button display a text once it is clicked and also
change the color of the text inside the button.
# Import Module
from tkinter import *

# create root window


root = Tk()

# root window title and dimension


[Link]("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
[Link]('350x200')

# adding a label to the root window


lbl = Label(root, text = "Are you a Geek?")
[Link]()

# function to display text when


# button is clicked
def clicked():
[Link](text = "I just got clicked")

# button widget with red color text


# inside
btn = Button(root, text = "Click me" ,
fg = "red", command=clicked)
# set Button grid
[Link](column=1, row=0)

# Execute Tkinter
[Link]()

Output:
Button added

After clicking “Click me”


6. Using the Entry() class we will create a text box for user input. To display the user input
text, we’ll make changes to the function clicked(). We can get the user entered text using the
get() function. When the Button after entering of the text, a default text concatenated with
the user text. Also change button grid location to column 2 as Entry() will be column 1.
# Import Module
from tkinter import *

# create root window


root = Tk()

# root window title and dimension


[Link]("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
[Link]('350x200')
# adding a label to the root window
lbl = Label(root, text = "Are you a Geek?")
[Link]()

# adding Entry Field


txt = Entry(root, width=10)
[Link](column =1, row =0)

# function to display user text when


# button is clicked
def clicked():

res = "You wrote" + [Link]()


[Link](text = res)

# button widget with red color text inside


btn = Button(root, text = "Click me" ,
fg = "red", command=clicked)
# Set Button Grid
[Link](column=2, row=0)

# Execute Tkinter
[Link]()
Output:
Entry Widget at column 2 row 0

Displaying user input text.


7. To add a menu bar, you can use Menu class. First, we create a menu, then we add our first
label, and finally, we assign the menu to our window. We can add menu items under any
menu by using add_cascade().
# Import Module
from tkinter import *

# create root window


root = Tk()

# root window title and dimension


[Link]("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
[Link]('350x200')

# adding menu bar in root window


# new item in menu bar labelled as 'New'
# adding more items in the menu bar
menu = Menu(root)
item = Menu(menu)
item.add_command(label='New')
menu.add_cascade(label='File', menu=item)
[Link](menu=menu)

# adding a label to the root window


lbl = Label(root, text = "Are you a Geek?")
[Link]()

# adding Entry Field


txt = Entry(root, width=10)
[Link](column =1, row =0)

# function to display user text when


# button is clicked
def clicked():

res = "You wrote" + [Link]()


[Link](text = res)

# button widget with red color text inside


btn = Button(root, text = "Click me" ,
fg = "red", command=clicked)
# Set Button Grid
[Link](column=2, row=0)
# Execute Tkinter
[Link]()
Output
This simple GUI covers the basics of Tkinter package. Similarly, you can add more widgets
and change their configurations as desired.
Tkinter Widgets
Tkinter is the GUI library of Python, it provides various controls, such as buttons, labels and
text boxes used in a GUI application. These controls are commonly called Widgets. The list
of commonly used Widgets are mentioned below –

Widget Description

The Label widget is used to provide


Label a single-line caption for other
widgets. It can also contain images.

The Button widget is used to


Button
display buttons in your application.

The Entry widget is used to display


Entry a single-line text field for accepting
values from a user.

The Menu widget is used to provide


various commands to a user. These
Menu
commands are contained inside
Menubutton.

The Canvas widget is used to draw


shapes, such as lines, ovals,
Canvas
polygons and rectangles, in your
application.

The Checkbutton widget is used to


display a number of options as
Checkbutton
checkboxes. The user can select
multiple options at a time.

The Frame widget is used as a


Frame container widget to organize other
widgets.

Listbox The Listbox widget is used to


Widget Description

provide a list of options to a user.

The Menubutton widget is used to


Menubutton
display menus in your application.

The Message widget is used to


Message display multiline text fields for
accepting values from a user.

The Radiobutton widget is used to


display a number of options as radio
Radiobutton
buttons. The user can select only
one option at a time.

The Scale widget is used to provide


Scale
a slider widget.

The Scrollbar widget is used to add


Scrollbar scrolling capability to various
widgets, such as list boxes.

The Text widget is used to display


Text
text in multiple lines.

The Toplevel widget is used to


Toplevel provide a separate window
container.

A labelframe is a simple container


widget. Its primary purpose is to act
LabelFrame
as a spacer or container for complex
window layouts.

This module is used to display


tkMessageBox
message boxes in your applications.

The Spinbox widget is a variant of


the standard Tkinter Entry widget,
Spinbox
which can be used to select from a
fixed number of values.

A PanedWindow is a container
widget that may contain any number
PanedWindow
of panes, arranged horizontally or
vertically.

Geometry Management
All Tkinter widgets have access to specific geometry management methods, which have the
purpose of organizing widgets throughout the parent widget area. Tkinter exposes the
following geometry manager classes: pack, grid, and place. Their description is mentioned
below –

S No. Widget Description

This geometry manager


organizes widgets in blocks
1 pack()
before placing them in the
parent widget.

This geometry manager


organizes widgets in a table-
2 grid()
like structure in the parent
widget.

This geometry manager


organizes widgets by placing
3 place()
them in a specific position in
the parent widget.

In this article, we have learned about GUI programming in Python and how to make GUI
in Python. GUI is a very demanded skill so you must know how to develop GUI using
Python. Hope this article helped you in creating GUI using Python.
Python - Databases and SQL

The Python programming language has powerful features for database programming. Python
supports various databases like SQLite, MySQL, Oracle, Sybase, PostgreSQL, etc. Python
also supports Data Definition Language (DDL), Data Manipulation Language (DML) and
Data Query Statements. The Python standard for database interfaces is the Python DB-API.
Most Python database interfaces adhere to this standard.
Here is the list of available Python database interfaces: Python Database Interfaces and APIs.
You must download a separate DB API module for each database you need to access.
In this chapter we will see the use of SQLite database in python programming language. It is
done by using python’s inbuilt, sqlite3 module. You should first create a connection object
that represents the database and then create some cursor objects to execute SQL statements.
Connect To Database
Following Python code shows how to connect to an existing database. If the database does
not exist, then it will be created and finally a database object will be returned.
#!/usr/bin/python

import sqlite3

conn = [Link]('[Link]')

print "Opened database successfully";


Here, you can also supply database name as the special name :memory: to create a database
in RAM. Now, let's run the above program to create our database [Link] in the current
directory. You can change your path as per your requirement. Keep the above code in
[Link] file and execute it as shown below. If the database is successfully created, then it
will display the following message.
$chmod +x [Link]
$./[Link]
Open database successfully

Create a Table
Following Python program will be used to create a table in the previously created database.
#!/usr/bin/python

import sqlite3

conn = [Link]('[Link]')
print "Opened database successfully";

[Link]('''CREATE TABLE COMPANY


(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";

[Link]()
When the above program is executed, it will create the COMPANY table in your [Link] and
it will display the following messages −
Opened database successfully
Table created successfully

Insert Operation
Following Python program shows how to create records in the COMPANY table created in
the above example.
#!/usr/bin/python

import sqlite3

conn = [Link]('[Link]')
print "Opened database successfully";

[Link]("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (1, 'Paul', 32, 'California', 20000.00 )");

[Link]("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");

[Link]("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");
[Link]("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");

[Link]()
print "Records created successfully";
[Link]()
When the above program is executed, it will create the given records in the COMPANY table
and it will display the following two lines −
Opened database successfully
Records created successfully

Select Operation
Following Python program shows how to fetch and display records from the COMPANY
table created in the above example.
#!/usr/bin/python

import sqlite3

conn = [Link]('[Link]')
print "Opened database successfully";

cursor = [Link]("SELECT id, name, address, salary from COMPANY")


for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

print "Operation done successfully";


[Link]()
When the above program is executed, it will produce the following result.
Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully


Update Operation
Following Python code shows how to use UPDATE statement to update any record and then
fetch and display the updated records from the COMPANY table.
#!/usr/bin/python

import sqlite3
conn = [Link]('[Link]')
print "Opened database successfully";

[Link]("UPDATE COMPANY set SALARY = 25000.00 where ID = 1")


[Link]
print "Total number of rows updated :", conn.total_changes

cursor = [Link]("SELECT id, name, address, salary from COMPANY")


for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

print "Operation done successfully";


[Link]()
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

Delete Operation
Following Python code shows how to use DELETE statement to delete any record and then
fetch and display the remaining records from the COMPANY table.
#!/usr/bin/python

import sqlite3

conn = [Link]('[Link]')
print "Opened database successfully";

[Link]("DELETE from COMPANY where ID = 2;")


[Link]()
print "Total number of rows deleted :", conn.total_changes

cursor = [Link]("SELECT id, name, address, salary from COMPANY")


for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

print "Operation done successfully";


[Link]()
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

Common questions

Powered by AI

In Python's SQLite implementation, both 'INSERT' and 'UPDATE' operations have distinct processes and effects on the database. 'INSERT' is used to add new records to a database table. For example, using the 'INSERT INTO' statement, new data is added to the specified columns of a table, as seen with the addition of records to the COMPANY table . Each successful insert increases the row count of the table. Conversely, 'UPDATE' modifies existing records rather than increasing their count. It utilizes the 'UPDATE SET' statement to change field values of existing rows based on a condition, as demonstrated by updating the SALARY field for a specific employee ID . While both operations require a connection to be opened and committed, INSERT results in data expansion, whereas UPDATE results in data modification without changing the table's overall size.

The Entry widget in Tkinter plays a significant role in facilitating user interaction by providing a simple interface for user input through single-line text fields . It allows users to input data, such as text or numerical values, directly into an application, which can then be processed or used within the program. The Entry widget supports methods like get(), which retrieves the user's input from the text field, enabling interactions like form submissions or real-time processing of input values when linked with event-handling functions . This capability makes Entry widgets essential for capturing user-entered data, thereby enhancing the interactivity and functionality of GUI applications in Python.

The grid geometry manager in Tkinter is significant for structured and organized placement of widgets like labels and entry fields next to each other. By treating the window's layout as a table of rows and columns, grid allows developers to specify exact row-column positions for widgets, facilitating precise alignment . In scenarios where a label and an entry field need to be adjacent, grid ensures they align within the same row, enhancing the GUI's visual coherence and user experience . This method stands out over pack, which lacks specific positional control, and place, which can be overly detailed for simple adjacent placements. Hence, grid is invaluable for creating clear, orderly interfaces where relative positioning is essential.

The 'grid' geometry manager in Tkinter organizes widgets in a two-dimensional table-like structure within the parent widget by specifying a row-column grid . It allows for precise control over the placement of widgets in terms of rows and columns, making it ideal for layouts that require alignment. On the other hand, 'pack' arranges widgets in blocks instead of specific positions and operates mainly with vertical and horizontal packing . 'Place' offers the most flexibility by explicitly positioning widgets at an exact coordinate location within the parent widget, using x and y positions . These differences make 'grid' suitable for more structured layouts, 'pack' for simpler stacking layouts, and 'place' for custom, pixel-perfect positioning.

Integrating a menu bar using the Menu class significantly enhances the user experience by providing a structured and predictable navigation system within a Tkinter application . Menus offer users easy access to various application functions, often grouped in logically consistent categories such as 'File', 'Edit', and 'Help', which improves accessibility and usability . By defining commands within menus, developers enable efficient execution of frequent actions, promoting ease of use and streamlining workflows. The presence of a menu bar aligns with common user interface design patterns, fostering a familiar environment that reduces learning curves and enhances intuitive interaction with the application. Overall, the addition of a well-organized menu bar can transform a basic GUI into a user-friendly interactive experience.

In Tkinter, the mainloop() function is crucial as it initiates the processing of events such as user interactions and system commands within the application . The absence of mainloop() means the application window would not become interactive or responsive, leading to confusion or a malfunctioning interface from the user's perspective . Interactive elements like buttons or entry widgets would not respond to user actions unless mainloop() is active. Additionally, as mainloop() enables continuous event monitoring, it contributes to maintaining the GUI's responsiveness and updates UI elements as needed, which is essential for a fluid and dynamic user experience. Consequently, using mainloop() appropriately ensures that the application provides a seamless and interactive user experience.

PyQt and Kivy are both libraries for creating GUI applications in Python but differ significantly in their use cases and features. PyQt is built on the Qt framework and provides a comprehensive set of widgets and features, making it suitable for traditional desktop applications . In contrast, Kivy is designed for developing modern, responsive interfaces, especially those for mobile apps and games, and supports multi-touch events . Additionally, PyQt applications often have a native look and feel on desktop platforms, whereas Kivy applications have a distinctive look and may require additional styling for native appearance. Furthermore, PyQt requires Python bindings for the Qt framework, which result in a steeper initial setup process compared to Kivy's ready-to-use cross-platform architecture.

Using SQLite with Python offers several advantages, such as its lightweight nature, which makes it ideal for small to medium-sized applications that don't require the overhead of a full database server . It allows for easy integration in Python applications using the built-in sqlite3 module, providing simple setup without needing separate server processes . However, there are disadvantages: SQLite is not suitable for high-concurrency applications due to its limited scalability with large numbers of simultaneous writes . Moreover, it lacks certain advanced database features found in more comprehensive systems like PostgreSQL or MySQL, such as fine-grained access control and advanced indexing . Consequently, while SQLite is efficient for prototyping and lightweight applications, it's less appropriate for high-demand, enterprise-level databases.

Developers might opt for alternatives to Tkinter depending on their specific project requirements and desired features. Tkinter is user-friendly and comes bundled with Python, making it accessible for beginners . However, it's considered more basic in functionality compared to other libraries like PyQt or wxPython, which offer a broader range of widgets and styling options . PyQt, for instance, provides a comprehensive set of tools for building complex, cross-platform applications similar to native desktop apps, often needed for commercial software. Furthermore, for applications targeting mobile platforms or requiring modern user interfaces, libraries such as Kivy are more suited due to their rich support for mobile-specific features and responsiveness . Consequently, while Tkinter is suitable for simple applications and rapid development, projects demanding higher functionality and modern aesthetics may benefit from these richer, more specialized libraries.

The Label widget in Tkinter serves as a means to display a single-line text caption or message within a GUI application . It is often used for labeling controls or providing instructions to the user. Besides text, the Label widget can also be configured to display images. This is achieved by creating a PhotoImage or BitmapImage object and passing it as the image parameter of the Label widget's constructor . Enhancing a label with an image provides greater versatility, allowing developers to include icons or logos in their GUIs to improve visual appeal and convey information more effectively.

You might also like