0% found this document useful (0 votes)
34 views

Tkinter

Uploaded by

kharatmaldhruv
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Tkinter

Uploaded by

kharatmaldhruv
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

IDE:

Python has become a well-liked programming language for application


development. The reason for its popularity lies in its simplicity in designing codes.
For writing simple and efficient Python codes, we need an Integrated Development
Environment (IDE).

An IDE consists of an editor and a compiler that we use to write and compile
programs. It has a combination of features required for developing software.

IDE makes the development process and programming much easier.

It interprets what we are typing and suggests the relevant keyword to insert.

We can distinguish between a class and a method as the IDE allocates different
colors to them. The IDE also gives different colors for the right and the wrong
keywords.

If we are writing a wrong keyword, it tries to predict the keyword that we intend
to write and auto completes it.

An IDE consists of a text editor window where we can write our programs.

It consists of a project editor window where we store all the necessary files of a
software project.

PyCharm is an integrated development environment (IDE) used in computer


programming, specifically for the Python language. It is developed by
the Czech company JetBrains

Some of the organizations such as Twitter, Facebook, Amazon, and Pinterest use
PyCharm as their Python IDE

Other Python IDE includes:

1. IDLE: When you install Python, IDLE is also installed by default. This
makes it easy to get started in Python.
2. Sublime Text 3: popular code editor that supports many languages including
Python. It's fast, highly customizable and has a huge community. However,
you can install packages such as debugging, auto-completion, code linting,
etc. There are also various packages for scientific development, Django,
Flask and so on.
3. Atom: Atom is an open-source code editor developed by Github that can be
used for Python development. Atom is highly customizable. You can install
packages as per your need.
4. PyCharm: PyCharm is an IDE for professional developers. It is created by
JetBrains, a company known for creating great software development tools.
PyCharm provides all major features that a good IDE should provide: code
completion, code inspections, error-highlighting and fixes, debugging,
version control system and code refactoring.
5. Visual Studio Code
6. Spyder
7. Eclipse's PyDev
8. Komodo IDE.

A Graphical User Interface(GUI) is the first thing your user sees and interacts with
when he opens your application or website.

A user interface usually includes a host of visual elements like icons, buttons,
graphics, displayed text, and several other forms of input, like checkbox, text input
boxes, and such.

Tkinter is Python's GUI (Graphical User Interface) package used in python


programming

Tkinter is the standard GUI library for Python.


Python when combined with Tkinter provides a fast and easy way to
create GUI applications.

Different GUI for python:

 PyQt5
 Tkinter
 Kivy
 wxPython
 PySimpleGUI
 PyForms
 Wax
 PyGUI

If you're developing a web app in Python, chances are you're leveraging a


framework.

A framework "is a code library that makes a developer's life easier when building
reliable, scalable, and maintainable web applications" by providing reusable code
or extensions for common operations.

A Web framework is a collection of packages or modules which allow developers


to write Web applications
There are a number of frameworks for Python, including
Flask
Tornado
Pyramid
Django
TurboGears
Web2py
Bottle
CherryPy
File handling, GUI & database programming:
What Is A Graphical User Interface (GUI)?

*Graphical User Interface (GUI) is nothing but a desktop application which helps
you to interact with the computers.

*They perform different tasks in the desktops, laptops and other electronic
devices.

*GUI apps like Text-Editors create, read, update and delete different types of files.

*Apps like Sudoku, Chess and Solitaire are games which you can play.

*GUI apps like Google Chrome, Firefox and Microsoft Edge browse through the
Internet.

-----------------------------------------------------------------------------------------------------

Python Libraries To Create Graphical User Interfaces:

Python has a plethora of libraries and these 4 stands out mainly when it comes to
GUI. There are as follows:

Kivy

Python QT

wxPython

Tkinter

Among all of these, Tkinter is the first choice for a LOT of learners and developers
just because of how simple and

easy it is.

Tkinter is one of the Python libraries which contains many functions for the
development of graphic user interface pages and windows. Login pages are
important for the development of any kind of mobile or web application.
https://www.javatpoint.com/how-to-append-element-in-the-list

Tkinter is actually an inbuilt Python module used to create simple GUI apps. It is
the most commonly used module for GUI apps in the Python.

You don’t need to worry about installation of the Tkinter module as it comes with
Python default in Python 3.6 version

So, kindly update Python if you’re using below versions.

The IDE or Text Editor


The IDE stands for Integrated Development Environment. There are various IDEs
but Pycharm is Python's most popular and useful text editor among them. It is
recommended for developing large and more complex applications. Here are using
the Pycharm to run python script.

-----------------------------------------------------------------------------------------------------

Fundamentals Of Tkinter:

1. first import the Tkinter model.

2. create the main window. (in this window that we are performing operations
and displaying visuals and everything )

3. add the widgets

4. lastly we enter the main event loop.(telling the code to keep displaying the
window until we manually close it)

----------------------------------------------------------------------------------------------------

Example: to create a blank window:


# !/usr/bin/python3
from tkinter import *
#creating the application main window.
top = Tk()
#Entering the event main loop
top.mainloop()

example:

import tkinter
window = tkinter.Tk()
window.geometry(“200x200”)
window.title("GUI") # to rename the title of the window window.title("GUI")
# pack is used to show the object in the window
label = tkinter.Label(window, text = "Hello World!").pack()
window.mainloop()

A label is nothing is but what output needs to be shown on the window.

In this case as you can already see, it is hello world

-------------------------------------------------------------------------------------------------------

Tkinter widgets
Widgets are used to build the python GUI applications.

Widgets are elements in the HTML. You will find different types of widgets to the
different types of elements in the Tkinter.

 Canvas – Canvas is used to draw shapes in your GUI.


 Button – Button widget is used to place the buttons in the Tkinter.
 Checkbutton – Checkbutton is used to create the check buttons in your
application. Note that you can select more than one option at a time.
 Entry – Entry widget is used to create input fields in the GUI.
 Frame – Frame is used as containers in the Tkinter.
 Label – Label is used to create a single line widgets like text, images etc.
 Menu – Menu is used to create menus in the GUI.

These widgets are the reason that Tkinter is so popular. It makes it really easy to
understand and use practically.

Python Tkinter Geometry


The Tkinter geometry specifies the method by using which, the widgets are represented
on display. The python Tkinter provides the following geometry methods.

1. The pack() method

2. The grid() method

3. The place() method

Python Tkinter pack() method


The pack() widget is used to organize widget in the block. The positions widgets added
to the python application using the pack() method can be controlled by using the
various options specified in the method call.

syntax
widget.pack(options)

example:
from tkinter import *
parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = "Black", fg = "black")
greenbutton.pack( side = RIGHT )
bluebutton = Button(parent, text = "Blue", fg = "blue")
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = "Green", fg = "red")
blackbutton.pack( side = BOTTOM)
parent.mainloop()

Python Tkinter grid() method


The grid() geometry manager organizes the widgets in the tabular form. We can specify
the rows and columns as the options in the method call. We can also specify the column
span (width) or rowspan(height) of a widget.
This is a more organized way to place the widgets to the python application. The syntax
to use the grid() is given below.

Syntax
widget.grid(options)
from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 2, column = 0)
parent.mainloop()

Python Tkinter place() method


The place() geometry manager organizes the widgets to the specific x and y
coordinates.

Syntax
widget.place(options)
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()

Python Tkinter Label


The Label is used to specify the container box where we can place the text or images.
This widget is used to provide the message to the user about other widgets used in the
python application.

There are the various options which can be specified to configure the text or the part of
the text shown in the Label.

The syntax to use the Label is given below.


Syntax
w = Label (master, options)

from tkinter import *


top = Tk()
top.geometry("400x250")
# creating label
uname = Label(top, text="Username").place(x=30, y=50)
# creating label
password = Label(top, text="Password").place(x=30, y=90)
sbmitbtn = Button(top, text="Submit", activebackground="pink",
activeforeground="blue").place(x=30, y=120)
e1 = Entry(top, width=20).place(x=100, y=50)
e2 = Entry(top, width=20).place(x=100, y=90)
top.mainloop()

import tkinter

window = tkinter.Tk()
# to rename the title of the window
window.title("GUI")
# pack is used to show the object in the window
label = tkinter.Label(window, font=("Arial Bold", 50) , text = "Welcome to
DataCamp's Tutorial on Tkinter!").pack()
window.mainloop()

Python Tkinter Button


The button widget is used to add various types of buttons to the python application.
Python allows us to configure the look of the button according to our requirements.
Various options can be set or reset depending upon the requirements.

We can also associate a method or function with a button which is called when the
button is pressed.

The button widget is very similar to the label widget. We create a variable and use
the widget syntax to define what the button has to say.
from tkinter import *
top = Tk()
top.geometry("200x100")
b = Button(top, text="Simple")
b.pack()
top.mainloop()

-------------------------------------------------------------------------------------------------------

import tkinter
window = tkinter.Tk()
window.title("Button GUI")
button_widget = tkinter.Button(window,text="Welcome to DataCamp's Tutorial
on Tkinter")
button_widget.pack()
tkinter.mainloop()

Button widget has a property for switching on/off. When a user clicks the button,
an event is triggered in the Tkinter.
Syntax: button_widget = tk.Button(widget,
option=placeholder) where widget is the argument for the parent
window/frame while option is a placeholder that can have various values
like foreground & background color, font, command (for function call),
image, height, and width of button.
Eg: text="Enter", bg="orange", fg="red"
import tkinter

# Let's create the Tkinter window.


window = tkinter.Tk()
window.title("GUI")

# You will first create a division with the help of Frame class and align them on
TOP and BOTTOM with pack() method.
top_frame = tkinter.Frame(window).pack()
bottom_frame = tkinter.Frame(window).pack(side = "bottom")

# Once the frames are created then you are all set to add widgets in both the
frames.
btn1 = tkinter.Button(top_frame, text = "Button1", fg = "red").pack() #'fg or
foreground' is for coloring the contents (buttons)

btn2 = tkinter.Button(top_frame, text = "Button2", fg = "green").pack()

btn3 = tkinter.Button(bottom_frame, text = "Button3", fg = "purple").pack(side =


"left") #'side' is used to left or right align the widgets

btn4 = tkinter.Button(bottom_frame, text = "Button4", fg = "orange").pack(side =


"left")

window.mainloop()

import tkinter
from tkinter import *
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
tkinter.Checkbutton(top, text = "Machine Learning",variable = CheckVar1,onvalue
= 1, offvalue=0).grid(row=0,sticky=W)
tkinter.Checkbutton(top, text = "Deep Learning", variable = CheckVar2, onvalue =
0, offvalue =1).grid(row=1,sticky=W)
top.mainloop()

from tkinter import *


top = Tk()
top.geometry("200x100")
def fun():
messagebox.showinfo("Hello", "Red Button clicked")

b1 = Button(top, text="Red", fg="red", bg="pink", pady=10, command = fun)


b2 = Button(top, text="Blue", fg="blue", bg="pink", pady=10)
b3 = Button(top, text="Green", fg="green", bg="pink", pady=10)
b4 = Button(top, text="Yellow", fg="yellow", bg="pink", pady=10)
b1.pack(side=LEFT)
b2.pack(side=RIGHT)
b3.pack(side=TOP)
b4.pack(side=BOTTOM)
top.mainloop()
Python Tkinter Canvas
The canvas widget is used to add the structured graphics to the python application. It is
used to draw the graph and plots to the python application. The syntax to use the
canvas is given below.

Syntax
w = canvas(parent, options)

 Canvas: Canvas is used to draw shapes in your GUI and supports various
drawing methods.
Syntax: canvas_widget = tk.Canvas(widget,
option=placeholder) where widget is the parameter for the parent
window/frame while option is a placeholder that can have various values
like border-width, background color, height and width of widget.
from tkinter import *
top = Tk()
top.geometry("200x200")
# creating a simple canvas
c = Canvas(top, bg="pink", height="200")
c.pack()
top.mainloop()

from tkinter import *


top = Tk()
top.geometry("200x200")
# creating a simple canvas
c = Canvas(top, bg="pink", height="200", width=200)
arc = c.create_arc((5, 10, 150, 200), start=0, extent=150, fill="white")
c.pack()
top.mainloop()

import tkinter
window = tkinter.Tk()
window.title("Button GUI")
canvas_widget =tkinter.Canvas(window, height=40 ,width=40)
canvas_widget.pack()
tkinter.mainloop()
Python Tkinter Checkbutton
The Checkbutton is used to track the user's choices provided to the application. In other
words, we can say that Checkbutton is used to implement the on/off selections.

The Checkbutton can contain the text or images. The Checkbutton is mostly used to
provide many choices to the user among which, the user needs to choose the one. It
generally implements many of many selections.

The syntax to use the checkbutton is given below.

Syntax
w = checkbutton(master, options)

 Checkbutton: Checkbutton records on-off or true-false state. It lets you can


select more than one option at a time and even leave it unchecked.
Syntax: checkbutton_widget = tk.CheckButton(widget,
option=placeholder) where widget is the parameter for the parent
window/frame while option is a placeholder that can have various values
like title, text, background & foreground color while widget is under the
cursor, font, image, etc.
from tkinter import *
top = Tk()
top.geometry("200x200")
checkvar1 = IntVar()
checkvar2 = IntVar()
checkvar3 = IntVar()
chkbtn1 = Checkbutton(top, text="C", variable=checkvar1, onvalue=0,
offvalue=0, height=2, width=10)
chkbtn2 = Checkbutton(top, text="C++", variable=checkvar2, onvalue=1,
offvalue=0, height=2, width=10)
chkbtn3 = Checkbutton(top, text="Java", variable=checkvar3, onvalue=1,
offvalue=0, height=2, width=10)
chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack()
top.mainloop()

import tkinter
from tkinter import *
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
CheckVar3 = IntVar()
tkinter.Checkbutton(top, text = "Machine Learning",variable = CheckVar1,onvalue
= 1, offvalue=0).grid(row=0,column=0)
tkinter.Checkbutton(top, text = "Deep Learning", variable = CheckVar2, onvalue =
1, offvalue =1).grid(row=1)
tkinter.Checkbutton(top, text = "Python", variable = CheckVar3, onvalue = 1,
offvalue =1).grid(row=2)

top.mainloop()

import tkinter
# Let's create the Tkinter window
window = tkinter.Tk()
window.title("GUI")

# You will create two text labels namely 'username' and 'password' and and two
input labels for them

tkinter.Label(window, text = "Username").grid(row = 0) #'username' is placed on


position 00 (row - 0 and column - 0)

# 'Entry' class is used to display the input-field for 'username' text label
tkinter.Entry(window).grid(row = 0, column = 1) # first input-field is placed on
position 01 (row - 0 and column - 1)

tkinter.Label(window, text = "Password").grid(row = 1) #'password' is placed on


position 10 (row - 1 and column - 0)

tkinter.Entry(window).grid(row = 1, column = 1) #second input-field is placed on


position 11 (row - 1 and column - 1)

# 'Checkbutton' class is for creating a checkbutton which will take a 'columnspan'


of width two (covers two columns)
tkinter.Checkbutton(window, text = "Keep Me Logged In").grid(columnspan = 2)

window.mainloop()

Python Tkinter Entry


The Entry widget is used to provde the single line text-box to the user to accept a value
from the user. We can use the Entry widget to accept the text strings from the user. It
can only be used for one line of text from the user. For multiple lines of text, we must
use the text widget.

The syntax to use the Entry widget is given below.

Syntax
w = Entry (parent, options)
rom tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text="Name").place(x=30, y=50)
email = Label(top, text="Email").place(x=30, y=90)
password = Label(top, text="Password").place(x=30, y=130)
sbmitbtn = Button(top, text="Submit", activebackground="pink",
activeforeground="blue").place(x=30, y=170)
e1 = Entry(top).place(x=80, y=50)
e2 = Entry(top).place(x=80, y=90)
e3 = Entry(top).place(x=95, y=130)
top.mainloop()

import tkinter as tk
from functools import partial

def call_result(label_result, n1, n2):


num1 = (n1.get())
num2 = (n2.get())
result = int(num1)+int(num2)
label_result.config(text="Result = %d" % result)
return

root = tk.Tk()
root.geometry('400x200+100+200')
root.title('Calculator')
number1 = tk.StringVar()
number2 = tk.StringVar()
labelNum1 = tk.Label(root, text="A").grid(row=1, column=0)
labelNum2 = tk.Label(root, text="B").grid(row=2, column=0)
labelResult = tk.Label(root)
labelResult.grid(row=7, column=2)
entryNum1 = tk.Entry(root, textvariable=number1).grid(row=1, column=2)
entryNum2 = tk.Entry(root, textvariable=number2).grid(row=2, column=2)
call_result = partial(call_result, labelResult, number1, number2)
buttonCal = tk.Button(root, text="Calculate", command=call_result).grid(row=3,
column=0)
root.mainloop()

Python Tkinter Listbox


The Listbox widget is used to display the list items to the user. We can place only text
items in the Listbox and all text items contain the same font and color.

The user can choose one or more items from the list depending upon the configuration.

The syntax to use the Listbox is given below.

w = Listbox(parent, options)

from tkinter import *


top = Tk()
top.geometry("200x250")
lbl = Label(top, text="A list of favourite countries...")
listbox = Listbox(top)
listbox.insert(1, "India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Austrelia")
lbl.pack()
listbox.pack()
top.mainloop()

Example 2: Deleting the active items from the list


from tkinter import *
top = Tk()
top.geometry("200x250")
lbl = Label(top, text="A list of favourite countries...")
listbox = Listbox(top)
listbox.insert(1, "India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Austrelia")

# this button will delete the selected item from the list
btn = Button(top, text="delete", command=lambda listbox=listbox:
listbox.delete(ANCHOR))
lbl.pack()
listbox.pack()
btn.pack()
top.mainloop()

Python Tkinter Menubutton


The Menubutton widget can be defined as the drop-down menu that is shown to the
user all the time. It is used to provide the user a option to select the appropriate choice
exist within the application.

The Menubutton is used to implement various types of menus in the python application.
A Menu is associated with the Menubutton that can display the choices of the
Menubutton when clicked by the user.

The syntax to use the python tkinter Menubutton is given below.

Syntax
w = Menubutton(Top, options)
from tkinter import *
top = Tk()
top.geometry("200x250")
menubutton = Menubutton(top, text="Language", relief=FLAT)
menubutton.grid()
menubutton.menu = Menu(menubutton)
menubutton["menu"] = menubutton.menu
menubutton.menu.add_checkbutton(label="Hindi", variable=IntVar())
menubutton.menu.add_checkbutton(label="English", variable=IntVar())
menubutton.pack()
top.mainloop()

Python Tkinter Menu


The Menu widget is used to create various types of menus (top level, pull down, and pop
up) in the python application.

The top-level menus are the one which is displayed just under the title bar of the parent
window. We need to create a new instance of the Menu widget and add various
commands to it by using the add() method.

The syntax to use the Menu widget is given below.

Syntax
w = Menu(top, options)
1. from tkinter import *
top = Tk()

def hello():
print("hello!")

# create a toplevel menu


menubar = Menu(top)
menubar.add_command(label="Hello!", command=hello)
menubar.add_command(label="Quit!", command=top.quit)

# display the menu


top.config(menu=menubar)
top.mainloop()

from tkinter import Toplevel, Button, Tk, Menu

top = Tk()
menubar = Menu(top)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")

file.add_separator()
file.add_command(label="Exit", command=top.quit)

menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar, tearoff=0)
edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")

menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar, tearoff=0)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
top.config(menu=menubar)
top.mainloop()
Python Tkinter Message
The Message widget is used to show the message to the user regarding the behaviour
of the python application. The message widget shows the text messages to the user
which can not be edited.

The message text contains more than one line. However, the message can only be
shown in the single font.

The syntax to use the Message widget is given below.

Syntax
w = Message(parent, options)
from tkinter import *

top = Tk()
top.geometry("100x100")
var = StringVar()
msg = Message(top, text="Welcome to Javatpoint")
msg.pack()
top.mainloop()

Python Tkinter Radiobutton


The Radiobutton widget is used to implement one-of-many selection in the python
application. It shows multiple choices to the user out of which, the user can select only
one out of them. We can associate different methods with each of the radiobutton.

We can display the multiple line text or images on the radiobuttons. To keep track the
user's selection the radiobutton, it is associated with a single variable. Each button
displays a single value for that particular variable.

The syntax to use the Radiobutton is given below.

Syntax
w = Radiobutton(top, options)
from tkinter import *

def selection():
selection = "You selected the option " + str(radio.get())
label.config(text=selection)

top = Tk()
top.geometry("300x150")
radio = IntVar()
lbl = Label(text="Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,command=selection)
R1.pack(anchor=W)
R2 = Radiobutton(top, text="C++", variable=radio, value=2,command=selection)
R2.pack(anchor=W)
R3 = Radiobutton(top, text="Java", variable=radio, value=3,command=selection)
R3.pack(anchor=W)

Binding or Command Functions


Binding or Command functions are those who are called whenever an event
occurs or is triggered.
import tkinter
# Let's create the Tkinter window
window = tkinter.Tk()
window.title("GUI")

# creating a function called DataCamp_Tutorial()


def DataCamp_Tutorial():
tkinter.Label(window, text = "GUI with Tkinter!").pack()

tkinter.Button(window, text = "Click Me!", command = DataCamp_Tutorial).pack()


window.mainloop()

Apart from invoking binding functions with a mouse click, the events can be
invoked with a mouse-move, mouse-over, clicking, scrolling, etc.

Mouse Clicking Event via the Bind Method


The Bind method provides you with a very simplistic approach to implementing
the mouse clicking events
import tkinter
# Let's create the Tkinter window
window = tkinter.Tk()
window.title("GUI")

#You will create three different functions for three different events
def left_click(event):
tkinter.Label(window, text = "Left Click!").pack()

def middle_click(event):
tkinter.Label(window, text = "Middle Click!").pack()

def right_click(event):
tkinter.Label(window, text = "Right Click!").pack()

window.bind("<Button-1>", left_click)
window.bind("<Button-2>", middle_click)
window.bind("<Button-3>", right_click)

window.mainloop()
Python Tkinter Frame
Python Tkinter Frame widget is used to organize the group of widgets. It acts like a
container which can be used to hold the other widgets. The rectangular areas of the
screen are used to organize the widgets to the python application.

The syntax to use the Frame widget is given below.

Syntax
w = Frame(parent, options)
from tkinter import *
top = Tk()
top.geometry("140x100")
frame = Frame(top)
frame.pack()
leftframe = Frame(top)
leftframe.pack(side=LEFT)
rightframe = Frame(top)
rightframe.pack(side=RIGHT)
btn1 = Button(frame, text="Submit", fg="red", activebackground="red")
btn1.pack(side=LEFT)
btn2 = Button(frame, text="Remove", fg="brown", activebackground="brown")
btn2.pack(side=RIGHT)
btn3 = Button(rightframe, text="Add", fg="blue", activebackground="blue")
btn3.pack(side=LEFT)
btn4 = Button(leftframe, text="Modify", fg="black", activebackground="white")
btn4.pack(side=RIGHT)
top.mainloop()

Alert Boxes
You can create alert boxes in the Tkinter using the messagebox method.
import tkinter.messagebox

# Let's create the Tkinter window


window = tkinter.Tk()
window.title("GUI")

# Let's create a alert box with 'messagebox' function


tkinter.messagebox.showinfo("Alert Message", "This is just a alert message!")

# Let's also create a question for the user and based upon the response [Yes or No
Question] display a message.
response = tkinter.messagebox.askquestion("Tricky Question", "Do you love Deep
Learning?")

# A basic 'if/else' block where if user clicks on 'Yes' then it returns 1 else it returns
0. For each response you will display a message with the help of 'Label' method.
if response == 1:
tkinter.Label(window, text = "Yes, offcourse I love Deep Learning!").pack()
else:
tkinter.Label(window, text = "No, I don't love Deep Learning!").pack()

window.mainloop()

import tkinter
from tkinter import *

# Let's create the Tkinter window


window = Tk()

# Then, you will define the size of the window in width(312) and height(324) using
the 'geometry' method
window.geometry("312x324")

# In order to prevent the window from getting resized you will call 'resizable'
method on the window
window.resizable(0, 0)

#Finally, define the title of the window


window.title("Calcualtor")

# Let's now define the required functions for the Calculator to function properly.

# 1. First is the button click 'btn_click' function which will continuously update the
input field whenever a number is entered or any button is pressed it will act as a
button click update.
def btn_click(item):
global expression
expression = expression + str(item)
input_text.set(expression)

# 2. Second is the button clear 'btn_clear' function clears the input field or
previous calculations using the button "C"
def btn_clear():
global expression
expression = ""
input_text.set("")

# 3. Third and the final function is button equal ("=") 'btn_equal' function which
will calculate the expression present in input field. For example: User clicks button
2, + and 3 then clicks "=" will result in an output 5.
def btn_equal():
global expression
result = str(eval(expression)) # 'eval' function is used for evaluating the string
expressions directly
# you can also implement your own function to evalute the expression istead of
'eval' function
input_text.set(result)
expression = ""

expression = ""
# In order to get the instance of the input field 'StringVar()' is used
input_text = StringVar()

# Once all the functions are defined then comes the main section where you will
start defining the structure of the calculator inside the GUI.

# The first thing is to create a frame for the input field


input_frame = Frame(window, width = 312, height = 50, bd = 0,
highlightbackground = "black", highlightcolor = "black", highlightthickness = 1)
input_frame.pack(side = TOP)

# Then you will create an input field inside the 'Frame' that was created in the
previous step. Here the digits or the output will be displayed as 'right' aligned
input_field = Entry(input_frame, font = ('arial', 18, 'bold'), textvariable =
input_text, width = 50, bg = "#eee", bd = 0, justify = RIGHT)
input_field.grid(row = 0, column = 0)
input_field.pack(ipady = 10) # 'ipady' is an internal padding to increase the height
of input field

# Once you have the input field defined then you need a separate frame which
will incorporate all the buttons inside it below the 'input field'
btns_frame = Frame(window, width = 312, height = 272.5, bg = "grey")
btns_frame.pack()

# The first row will comprise of the buttons 'Clear (C)' and 'Divide (/)'
clear = Button(btns_frame, text = "C", fg = "black", width = 32, height = 3, bd = 0,
bg = "#eee", cursor = "hand2", command = lambda: btn_clear()).grid(row = 0,
column = 0, columnspan = 3, padx = 1, pady = 1)
divide = Button(btns_frame, text = "/", fg = "black", width = 10, height = 3, bd = 0,
bg = "#eee", cursor = "hand2", command = lambda: btn_click("/")).grid(row = 0,
column = 3, padx = 1, pady = 1)
# The second row will comprise of the buttons '7', '8', '9' and 'Multiply (*)'
seven = Button(btns_frame, text = "7", fg = "black", width = 10, height = 3, bd = 0,
bg = "#fff", cursor = "hand2", command = lambda: btn_click(7)).grid(row = 1,
column = 0, padx = 1, pady = 1)
eight = Button(btns_frame, text = "8", fg = "black", width = 10, height = 3, bd = 0,
bg = "#fff", cursor = "hand2", command = lambda: btn_click(8)).grid(row = 1,
column = 1, padx = 1, pady = 1)
nine = Button(btns_frame, text = "9", fg = "black", width = 10, height = 3, bd = 0,
bg = "#fff", cursor = "hand2", command = lambda: btn_click(9)).grid(row = 1,
column = 2, padx = 1, pady = 1)
multiply = Button(btns_frame, text = "*", fg = "black", width = 10, height = 3, bd =
0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("*")).grid(row = 1,
column = 3, padx = 1, pady = 1)

# The third row will comprise of the buttons '4', '5', '6' and 'Subtract (-)'
four = Button(btns_frame, text = "4", fg = "black", width = 10, height = 3, bd = 0,
bg = "#fff", cursor = "hand2", command = lambda: btn_click(4)).grid(row = 2,
column = 0, padx = 1, pady = 1)
five = Button(btns_frame, text = "5", fg = "black", width = 10, height = 3, bd = 0, bg
= "#fff", cursor = "hand2", command = lambda: btn_click(5)).grid(row = 2, column
= 1, padx = 1, pady = 1)
six = Button(btns_frame, text = "6", fg = "black", width = 10, height = 3, bd = 0, bg
= "#fff", cursor = "hand2", command = lambda: btn_click(6)).grid(row = 2, column
= 2, padx = 1, pady = 1)
minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0,
bg = "#eee", cursor = "hand2", command = lambda: btn_click("-")).grid(row = 2,
column = 3, padx = 1, pady = 1)

# The fourth row will comprise of the buttons '1', '2', '3' and 'Addition (+)'
one = Button(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0,
bg = "#fff", cursor = "hand2", command = lambda: btn_click(1)).grid(row = 3,
column = 0, padx = 1, pady = 1)
two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0,
bg = "#fff", cursor = "hand2", command = lambda: btn_click(2)).grid(row = 3,
column = 1, padx = 1, pady = 1)
three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0,
bg = "#fff", cursor = "hand2", command = lambda: btn_click(3)).grid(row = 3,
column = 2, padx = 1, pady = 1)
plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0,
bg = "#eee", cursor = "hand2", command = lambda: btn_click("+")).grid(row = 3,
column = 3, padx = 1, pady = 1)

# Finally, the fifth row will comprise of the buttons '0', 'Decimal (.)', and 'Equal To
(=)'
zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0,
bg = "#fff", cursor = "hand2", command = lambda: btn_click(0)).grid(row = 4,
column = 0, columnspan = 2, padx = 1, pady = 1)
point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0,
bg = "#eee", cursor = "hand2", command = lambda: btn_click(".")).grid(row = 4,
column = 2, padx = 1, pady = 1)
equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0,
bg = "#eee", cursor = "hand2", command = lambda: btn_equal()).grid(row = 4,
column = 3, padx = 1, pady = 1)

window.mainloop()

Python Tkinter Scrollbar


The scrollbar widget is used to scroll down the content of the other widgets like listbox,
text, and canvas. However, we can also create the horizontal scrollbars to the Entry
widget.
The syntax to use the Scrollbar widget is given below.

Syntax
w = Scrollbar(top, options)

from tkinter import *

top = Tk()
sb = Scrollbar(top)
sb.pack(side=RIGHT, fill=Y)

mylist = Listbox(top, yscrollcommand=sb.set)

for line in range(30):


mylist.insert(END, "Number " + str(line))

mylist.pack()
sb.config(command=mylist.yview)
mainloop()

label = Label(top)
label.pack()
top.mainloop()

Tkinter Toplevel
The Toplevel widget is used to create and display the toplevel windows which are
directly managed by the window manager. The toplevel widget may or may not have
the parent window on the top of them.

The toplevel widget is used when a python application needs to represent some extra
information, pop-up, or the group of widgets on the new window.

from tkinter import *


root = Tk()
root.geometry("200x200")

def open():
top = Toplevel(root)
top.mainloop()

btn = Button(root, text="open", command=open)


btn.place(x=75, y=50)
root.mainloop()
Python Tkinter Spinbox
The Spinbox widget is an alternative to the Entry widget. It provides the range of values
to the user, out of which, the user can select the one.

It is used in the case where a user is given some fixed number of values to choose from.

We can use various options with the Spinbox to decorate the widget. The syntax to use
the Spinbox is given below.

Syntax
w = Spinbox(top, options)

from tkinter import *


top = Tk()

top.geometry("200x200")
spin = Spinbox(top, from_=0, to=25)
spin.pack()

top.mainloop()

Tkinter PanedWindow
The PanedWindow widget acts like a Container widget which contains one or more child
widgets (panes) arranged horizontally or vertically. The child panes can be resized by
the user, by moving the separator lines known as sashes by using the mouse.

Each pane contains only one widget. The PanedWindow is used to implement the
different layouts in the python applications.

The syntax to use the PanedWindow is given below.

Syntax
w= PanedWindow(master, options)

from tkinter import *

def add():
a = int(e1.get())
b = int(e2.get())
leftdata = str(a + b)
left.insert(1, leftdata)
w1 = PanedWindow()
w1.pack()
left = Entry(w1, bd=5)
w1.add(left)
w2 = PanedWindow(w1,orient=VERTICAL)
w1.add(w2)
e1 = Entry(w2)
e2 = Entry(w2)
w2.add(e1)
w2.add(e2)
bottom = Button(w2, text="Add", command=add)
w2.add(bottom)
mainloop()

Tkinter LabelFrame
The LabelFrame widget is used to draw a border around its child widgets. We can also
display the title for the LabelFrame widget. It acts like a container which can be used to
group the number of interrelated widgets such as Radiobuttons.

This widget is a variant of the Frame widget which has all the features of a frame. It also
can display a label.

The syntax to use the LabelFrame widget is given below.

Syntax
w = LabelFrame(top, options)

from tkinter import *

top = Tk()
top.geometry("300x200")

labelframe1 = LabelFrame(top, text="Positive Comments")


labelframe1.pack(fill="both", expand="yes")

toplabel = Label(labelframe1, text="Place to put the positive comments")


toplabel.pack()

labelframe2 = LabelFrame(top, text="Negative Comments")


labelframe2.pack(fill="both", expand="yes")

bottomlabel = Label(labelframe2, text="Place to put the negative comments")


bottomlabel.pack()

top.mainloop()

Tkinter messagebox
The messagebox module is used to display the message boxes in the python
applications. There are the various functions which are used to display the relevant
messages depending upon the application requirements.

The syntax to use the messagebox is given below.

Syntax
messagebox.function_name(title, message [, options])

from tkinter import *


from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.showinfo("MessageBox", "InformationTechnology")
top.mainloop()

showwarning()
This method is used to display the warning to the user. Consider the following example.

from tkinter import *


from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.showwarning("warning", "Warning")
top.mainloop()

showerror()
This method is used to display the error message to the user. Consider the following
example.
from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.showerror("error", "Error")
top.mainloop()

askquestion()
This method is used to ask some question to the user which can be answered in yes or
no. Consider the following example.

from tkinter import *


from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.askquestion("Confirm", "Are you sure?")
top.mainloop()

askokcancel()
This method is used to confirm the user's action regarding some application activity.
Consider the following example.

from tkinter import *


from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.askokcancel("Redirect", "Redirecting you to www.javatpoint.com")
top.mainloop()

askyesno()
This method is used to ask the user about some action to which, the user can answer in
yes or no. Consider the following example.

from tkinter import *


from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.askyesno("Application", "Got It?")
top.mainloop()
askretrycancel()
This method is used to ask the user about doing a particular task again or not. Consider
the following example.

from tkinter import *


from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.askretrycancel("Application", "try again?")

top.mainloop()

You might also like