Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
213 views

GUI in Python

- Tkinter is the standard GUI library for Python and allows building cross-platform desktop applications. - The main elements are windows (Tk class), which contain widgets like labels, buttons, text boxes. - Creating a basic GUI involves importing Tkinter, making a window, and adding widgets like labels and buttons that can contain text or trigger functions. - Common widgets include labels to display text, buttons to add interactivity, and text boxes (entries or text widgets) to accept user input.

Uploaded by

ANKUR CHOUDHARY
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
213 views

GUI in Python

- Tkinter is the standard GUI library for Python and allows building cross-platform desktop applications. - The main elements are windows (Tk class), which contain widgets like labels, buttons, text boxes. - Creating a basic GUI involves importing Tkinter, making a window, and adding widgets like labels and buttons that can contain text or trigger functions. - Common widgets include labels to display text, buttons to add interactivity, and text boxes (entries or text widgets) to accept user input.

Uploaded by

ANKUR CHOUDHARY
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

GUI in Python

Python GUI Programming With Tkinter


GUI Programming
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. Visual
elements are rendered using native operating system elements, so applications
built with Tkinter look like they belong on the platform where they’re run.

Although Tkinter is considered the de-facto Python GUI framework, it’s not
without criticism. One notable criticism is that GUIs built with Tkinter look
outdated. If you want a shiny, modern interface, then Tkinter may not be what
you’re looking for.

However, 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 sheen is unnecessary, and
the top priority is to build something that’s functional and cross-platform
quickly.
Building Your First Python GUI Application
With Tkinter

The foundational element of a Tkinter GUI is


the window. Windows are the containers in
which all other GUI elements live. These other
GUI elements, such as text boxes, labels, and
buttons, are known as widgets. Widgets are
contained inside of windows.
First Program
With your Python shell open, the first thing you
need to do is import the Python GUI Tkinter
module:
>>> import tkinter as tk
A window is an instance of Tkinter’s Tk class. Go
ahead and create a new window and assign it to
the variable window:
>>>window = tk.Tk()
Adding a Widget
Now that you have a window, you can add a
widget. Use the tk.Label class to add some text to a
window. Create a Label widget with the text "Hello,
Tkinter" and assign it to a variable called greeting:
>>> greeting = tk.Label(text="Hello, Tkinter")
The window you created earlier doesn’t change.
You just created a Label widget, but you haven’t
added it to the window yet. There are several ways
to add widgets to a window. Right now, you can
use the Label widget’s .pack() method:
>>> greeting.pack()
When you .pack() a widget into a window, Tkinter
sizes the window as small as it can while still fully
encompassing the widget. Now execute the
following:
>>> window.mainloop()
window.mainloop() tells Python to run the
Tkinter event loop. This method listens for events,
such as button clicks or keypresses, and blocks any
code that comes after it from running until the
window it’s called on is closed. Go ahead and close
the window you’ve created, and you’ll see a new
prompt displayed in the shell.
Working With Widgets

Widgets are the bread and butter of the Python


GUI framework Tkinter. They are the elements
through which users interact with your program.
Each widget in Tkinter is defined by a class. Here
are some of the widgets available:
Widget Class Description
Label A widget used to display text on the screen

Button A button that can contain text and can


perform an action when clicked

Entry A text entry widget that allows only a single


line of text

Text A text entry widget that allows multiline


text entry

Frame A rectangular region used to group related


widgets or provide padding between
widgets
Displaying Text and Images With Label Widgets

Label widgets are used to display text or


images. The text displayed by a Label widget
can’t be edited by the user. It’s for display
purposes only. You can create a Label widget by
instantiating the Label class and passing a string
 to the text parameter:
label = tk.Label(text="Hello, Tkinter")
Label widgets display text with the default system text
color and the default system text background color.
These are typically black and white, respectively, but
you may see different colors if you have changed
these settings in your operating system.
You can control Label text and background colors
using the foreground and background parameters:
label = tk.Label( text="Hello, Tkinter",
foreground="white", # Set the text color to white
background="black" # Set the background color to
black )
There are numerous valid color names, including:
"red"
"orange"
"yellow"
"green"
"blue"
"purple"
Many of the HTML color names work with Tkinter.
A chart with most of the valid color names is
available here. 
You can also specify a color using hexadecimal RGB values:
label = tk.Label(text="Hello, Tkinter",
background="#34A2FE")
This sets the label background to a nice, light blue color.
Hexadecimal RGB values are more cryptic than named
colors, but they’re also more flexible. Fortunately, there are 
tools available that make getting hexadecimal color codes
relatively painless.
If you don’t feel like typing
out foreground and background all the time, then you can
use the shorthand fg and bg parameters to set the
foreground and background colors:
label = tk.Label(text="Hello, Tkinter", fg="white",
bg="black")
You can also control the width and height of a label with
the width and height parameters:
label = tk.Label( text="Hello, Tkinter", fg="white", bg="black",
width=10, height=10 )
It may seem strange that the label in the window isn’t square even
though the width and height are both set to 10. This is because the
width and height are measured in text units. One horizontal text unit is
determined by the width of the character "0", or the number zero, in
the default system font. Similarly, one vertical text unit is determined
by the height of the character "0".
Eg. to use image in label
import tkinter as tk
w=tk.Tk()
pimg=tk.PhotoImage(file="desert.png")
l=tk.Label(image=pimg, width=400,height=400)
l.pack()
Displaying Clickable Buttons With Button Widgets

Button widgets are used to display clickable buttons. They can be


configured to call a function whenever they’re clicked. For now,
take a look at how to create and style a Button.
There are many similarities between Button and Label widgets. In
many ways, a Button is just a Label that you can click! The same
keyword arguments you use to create and style a Label will work
with Button widgets. For example, the following code creates
a Button with a blue background and yellow text. It also sets the
width and height to 25 and 5 text units, respectively:
button = tk.Button( text="Click me!", width=25, height=5,
bg="blue", fg="yellow", )
Getting User Input With Entry Widgets

When you need to get a little bit of text from a user,


like a name or an email address, use
an Entry widget. They display a small text box that
the user can type some text into. Creating and
styling an Entry widget works pretty much exactly
like Label and Button widgets. For example, the
following code creates a widget with a blue
background, some yellow text, and a width
of 50 text units:
entry = tk.Entry(fg="yellow", bg="blue", width=50)
• The interesting bit about Entry widgets isn’t
how to style them, though. It’s how to use
them to get input from a user. There are
three main operations that you can perform
with Entry widgets:
• Retrieving text with .get()
• Deleting text with .delete()
• Inserting text with .insert()
>>> import tkinter as tk
>>> window = tk.Tk()
>>> label = tk.Label(text="Name")
>>> entry = tk.Entry()
>>> label.pack()
>>> entry.pack()
Now you’ve got some text entered into the Entry widget, but
that text hasn’t been sent to your program yet. You can
use .get() to retrieve the text and assign it to a variable
called name:
>>> name = entry.get()
You can .delete() text as well. This method takes an integer
argument that tells Python which character to remove. For
example, the code block below shows
how .delete(0) deletes the first character from the Entry:
>>> entry.delete(0)
Note that, just like Python string objects, text in
an Entry widget is indexed starting with 0.
If you need to remove several characters from an Entry,
then pass a second integer argument
to .delete() indicating the index of the character where
deletion should stop. For example, the following code
deletes the first four letters in the Entry:
>>> entry.delete(0, 4)
Entry.delete() works just like string slicing. The
first argument determines the starting index,
and the deletion continues up to but not
including the index passed as the second
argument. Use the special constant tk.END for
the second argument of .delete() to remove all
text in an Entry:
>>> entry.delete(0, tk.END)
On the opposite end of the spectrum, you can
also .insert() text into an Entry widget:
>>> entry.insert(0, "Python")
If an Entry already contains some text,
then .insert() will insert the new text at the
specified position and shift all existing text to
the right:
>>> entry.insert(0, "Real ")
Getting Multiline User Input With Text Widgets

Text widgets are used for entering text, just


like Entry widgets. The difference is that Text widgets
may contain multiple lines of text. With
a Text widget, a user can input a whole paragraph or
even several pages of text! Just like Entry widgets,
there are three main operations you can perform
with Text widgets:
• Retrieve text with .get()
• Delete text with .delete()
• Insert text with .insert()
In your Python shell, create a new blank window
and .pack() a Text() widget into it:
>>> window = tk.Tk()
>>> text_box = tk.Text()
>>> text_box.pack()
Just like Entry widgets, you can retrieve the text
from a Text widget using .get(). However,
calling .get() with no arguments doesn’t return the
full text in the text box like it does for Entry widgets.
It raises an exception:
>>> text_box.get()
Text.get() required at least one argument. Calling .get() with a single
index returns a single character. To retrieve several characters, you
need to pass a start index and an end index. Indices in Text widgets
work differently than Entry widgets. Since Text widgets can have
several lines of text, an index must contain two pieces of information:
• The line number of a character
• The position of a character on that line
Line numbers start with 1, and character positions start with 0. To
make an index, you create a string of the form "<line>.<char>",
replacing <line> with the line number and <char> with the character
number. For example, "1.0" represents the first character on the first
line, and "2.3" represents the fourth character on the second line.
Use the index "1.0" to get the first letter from the text box you
created earlier:
>>> text_box.get("1.0")
• There are five letters in the word "Hello", and the
character number of o is 4, since character
numbers start from 0, and the word "Hello" starts
at the first position in the text box. Just like
Python string slices, in order to get the entire
word "Hello" from the text box, the end index
must be one more than the index of the last
character to be read.
• So, to get the word "Hello" from the text box,
use "1.0" for the first index and "1.5" for the
second index:
• >>> text_box.get("1.0", "1.5")
To get the word "World" on the second line of
the text box, change the line numbers in each
index to 2:
>>> text_box.get("2.0", "2.5")
To get all of the text in a text box, set the
starting index in "1.0" and use the
special tk.END constant for the second index:
>>> text_box.get("1.0", tk.END)
Notice that text returned by .get() includes any newline
characters. You can also see from this example that every
line in a Text widget has a newline character at the end,
including the last line of text in the text box.
.delete() is used to delete characters from a text box. It work
just like .delete() for Entry widgets. There are two ways to
use .delete():
• With a single argument
• With two arguments
Using the single-argument version, you pass to .delete() the
index of a single character to be deleted. For example, the
following deletes the first character H from the text box:
>>> text_box.delete("1.0")
• With the two-argument version, you pass two indices
to delete a range of characters starting at the first
index and up to, but not including, the second index.
• For example, to delete the remaining "ello" on the first
line of the text box, use the indices "1.0" and "1.4":
>>> text_box.delete("1.0", "1.4")
 There’s still a character on the first line. It’s a newline
character! You can verify this using .get():
>>> text_box.get("1.0")
If you delete that character, then the rest of the
contents of the text box will shift up a line:
>>> text_box.delete("1.0")
Try to clear out the rest of the text in the text box. Set "1.0" as the
start index and use tk.END for the second index:
>>> text_box.delete("1.0", tk.END)
You can insert text into a text box using .insert():
>>> text_box.insert("1.0", "Hello")
This inserts the word "Hello" at the beginning of the text box,
using the same "<line>.<column>" format used by .get() to
specify the insertion position:
 to insert the word "World" on the second line:
>>> text_box.insert("2.0", "World")
If you want to insert text onto a new line, then you need to insert
a newline character manually into the string being inserted:
>>> text_box.insert("2.0", "\nWorld")
.insert() will do one of two things:
• Insert text at the specified position if there’s already text at
or after that position.
• Append text to the specified line if the character number is
greater than the index of the last character in the text box.
It’s usually impractical to try and keep track of what the index
of the last character is. The best way to insert text at the end
of a Text widget is to pass tk.END to the first parameter
of .insert():
text_box.insert(tk.END, "Put me at the end!")
Don’t forget to include the newline character (\n) at the
beginning of the text if you want to put it on a new line:
text_box.insert(tk.END, "\nPut me on a new line!")
Assigning Widgets to Frames With Frame Widgets

Frame widgets are important for organizing the


layout of your widgets in an application.
The following script creates a blank Frame widget and
assigns it to the main application window:
import tkinter as tk
window = tk.Tk()
frame = tk.Frame()
frame.pack()
window.mainloop()
frame.pack() packs the frame into the window so
that the window sizes itself as small as possible
to encompass the frame.
 Assign a widget to a frame by setting the
widget’s master attribute:
frame = tk.Frame()
label = tk.Label(master=frame)
Two Frame widgets called frame_a and frame_b.
In this script, frame_a contains a label with the
text "I'm in Frame A", and frame_b contains the
label "I'm in Frame B". Here’s one way to do this:
import tkinter as tk
window = tk.Tk()
frame_a = tk.Frame()
frame_b = tk.Frame()
label_a = tk.Label(master=frame_a, text="I'm in Frame A")
label_a.pack()
label_b = tk.Label(master=frame_b, text="I'm in Frame B")
label_b.pack()
frame_a.pack()
frame_b.pack()
window.mainloop()
Adjusting Frame Appearance With Reliefs

Frame widgets can be configured with


a relief attribute that creates a border around the
frame. You can set relief to be any of the following
values:
• tk.FLAT: Has no border effect (the default value).
• tk.SUNKEN: Creates a sunken effect.
• tk.RAISED: Creates a raised effect.
• tk.GROOVE: Creates a grooved border effect.
• tk.RIDGE: Creates a ridged effect.
To apply the border effect, you must set
the borderwidth attribute to a value greater
than 1. This attribute adjusts the width of the
border in pixels. Here’s a script that packs
five Frame widgets into a window, each with a
different value for the relief argument:
import tkinter as tk
border_effects = { "flat": tk.FLAT, "sunken":
tk.SUNKEN, "raised": tk.RAISED, "groove":
tk.GROOVE, "ridge": tk.RIDGE, }
window = tk.Tk()
for relief_name, relief in border_effects.items():
frame = tk.Frame(master=window, relief=relief, borderwidth=5)
frame.pack(side=tk.LEFT)
label = tk.Label(master=frame, text=relief_name)
label.pack()
window.mainloop()
Controlling Layout With Geometry Managers

Application layout in Tkinter is controlled with geometry


managers. While .pack() is an example of a geometry
manager, it isn’t the only one. Tkinter has two others:
• .place()
• .grid()
Each window and Frame in your application can use only
one geometry manager. However, different frames can
use different geometry managers, even if they’re
assigned to a frame or window using another geometry
manager.
The .pack() Geometry Manager

.pack() uses a packing algorithm to place widgets in a Frame or


window in a specified order. For a given widget, the packing
algorithm has two primary steps:
• Compute a rectangular area called a parcel that’s just tall (or
wide) enough to hold the widget and fills the remaining width
(or height) in the window with blank space.
• Center the widget in the parcel unless a different location is
specified.
.pack() is powerful, but it can be difficult to visualize. The best
way to get a feel for .pack() is to look at some examples. See what
happens when you .pack() three Label widgets into a Frame:
import tkinter as tk
window = tk.Tk()
frame1 = tk.Frame(master=window, width=100, height=100,
bg="red")
frame1.pack()
frame2 = tk.Frame(master=window, width=50, height=50,
bg="yellow")
frame2.pack()
frame3 = tk.Frame(master=window, width=25, height=25,
bg="blue")
frame3.pack()
window.mainloop()

.pack() places each Frame below the previous one by default, in the


order that they’re assigned to the window
• There are three invisible parcels containing each of the
three Frame widgets. Each parcel is as wide as the
window and as tall as the Frame that it contains. Since
no anchor point was specified when .pack() was called for
each Frame, they’re all centered inside of their parcels.
That’s why each Frame is centered in the window.
• .pack() accepts some keyword arguments for more
precisely configuring widget placement. For example, you
can set the fill keyword argument to specify in
which direction the frames should fill. The options
are tk.X to fill in the horizontal direction, tk.Y to fill
vertically, and tk.BOTH to fill in both directions. Here’s
how you would stack the three frames so that each one
fills the whole window horizontally:
import tkinter as tk
window = tk.Tk()
frame1 = tk.Frame(master=window, height=100, bg="red")
frame1.pack(fill=tk.X)
frame2 = tk.Frame(master=window, height=50, bg="yellow")
frame2.pack(fill=tk.X)
frame3 = tk.Frame(master=window, height=25, bg="blue")
frame3.pack(fill=tk.X)
window.mainloop()

The width is not set on any of the Frame widgets. width is no longer necessary


because each frame sets .pack() to fill horizontally, overriding any width you may
set.

One of the nice things about filling the window with .pack() is that the fill is
responsive to window resizing. Try widening the window generated by the previous
script to see how this works. As you widen the window, the width of the
three Frame widgets grow to fill the window:

Notice, though, that the Frame widgets don’t expand in the vertical direction.


The side keyword argument of .pack() specifies
on which side of the window the widget should
be placed. These are the available options:
• tk.TOP
• tk.BOTTOM
• tk.LEFT
• tk.RIGHT
If you don’t set side, then .pack() will
automatically use tk.TOP and place new widgets
at the top of the window, or at the top-most
portion of the window that isn’t already
occupied by a widget. For example, the
following script places three frames side-by-side
from left to right and expands each frame to fill
the window vertically:
import tkinter as tk
window = tk.Tk()
frame1 = tk.Frame(master=window, width=200,
height=100, bg="red")
frame1.pack(fill=tk.Y, side=tk.LEFT)
frame2 = tk.Frame(master=window, width=100,
bg="yellow")
frame2.pack(fill=tk.Y, side=tk.LEFT)
frame3 = tk.Frame(master=window, width=50,
bg="blue")
frame3.pack(fill=tk.Y, side=tk.LEFT)
window.mainloop()
This time, we have to specify the height keyword
argument on at least one of the frames to force
the window to have some height.

When you set fill=tk.X to make the frames


responsive when you resized the window
horizontally, you can set fill=tk.Y to make the
frames responsive when you resize the window
vertically:
To make the layout truly responsive, you can set an initial size for
your frames using the width and height attributes. Then, set
the fill keyword argument of .pack() to tk.BOTH and set
the expand keyword argument to True:

import tkinter as tk
window = tk.Tk()
frame1 = tk.Frame(master=window, width=200, height=100,
bg="red")
frame1.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
frame2 = tk.Frame(master=window, width=100, bg="yellow")
frame2.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
frame3 = tk.Frame(master=window, width=50, bg="blue")
frame3.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
window.mainloop()
The .place() Geometry Manager
• You can use .place() to control the precise
location that a widget should occupy in a window
or Frame. You must provide two keyword
arguments, x and y, which specify the x- and y-
coordinates for the top-left corner of the widget.
Both x and y are measured in pixels, not text units.
• The origin (where x and y are both 0) is the top-left
corner of the Frame or window. So, you can think of
the y argument of .place() as the number of pixels
from the top of the window, and the x argument as
the number of pixels from the left of the window.
Here’s an example of how the .place() geometry manager
works:
import tkinter as tk
window = tk.Tk()
frame = tk.Frame(master=window, width=150, height=150)
frame.pack()
label1 = tk.Label(master=frame, text="I'm at (0, 0)",
bg="red")
label1.place(x=0, y=0)
label2 = tk.Label(master=frame, text="I'm at (75, 75)",
bg="yellow")
label2.place(x=75, y=75)
window.mainloop()
.place() is not used often. It has two main
drawbacks:
• Layout can be difficult to manage
with .place(). This is especially true if your
application has lots of widgets.
• Layouts created with .place() are not
responsive. They don’t change as the window
is resized.
The .grid() Geometry Manager

• The geometry manager you’ll likely use most often


is .grid(), which provides all the power of .pack() in a
format that’s easier to understand and maintain.
• .grid() works by splitting a window or Frame into
rows and columns. You specify the location of a
widget by calling .grid() and passing the row and
column indices to the row and column keyword
arguments, respectively. Both row and column
indices start at 0, so a row index of 1 and a column
index of 2 tells .grid() to place a widget in the third
column of the second row.
The following script creates a 3 × 3 grid of frames
with Label widgets packed into them:
import tkinter as tk
window = tk.Tk()
for i in range(3):
for j in range(3):
frame = tk.Frame
( master=window,
relief=tk.RAISED,
borderwidth=1 ) frame.grid(row=i,
column=j)
label = tk.Label(
master=frame,
text=f"Row {i}\nColumn {j}")
label.pack()
window.mainloop()
Two geometry managers are being used in this example. Each Frame is
attached to the window with the .grid() geometry manager:

import tkinter as tk
window = tk.Tk()
for i in range(3):
for j in range(3):
frame = tk.Frame(
master=window,
relief=tk.RAISED,
borderwidth=1 )
frame.grid(row=i, column=j)
label = tk.Label(
master=frame,
text=f"Row {i}\nColumn {j}")
label.pack()
window.mainloop()
Each label is attached to its master Frame with .pack():

import tkinter as tk
window = tk.Tk()
for i in range(3):
for j in range(3):
frame = tk.Frame( master=window, relief=tk.RAISED,
borderwidth=1 )
frame.grid(row=i, column=j)
label = tk.Label(master=frame, text=f"Row {i}\nColumn
{j}")
label.pack()
window.mainloop()
Using command

Every Button widget has a command attribute that


you can assign to a function. Whenever the button
is pressed, the function is executed.
def increase():
value = int(lbl_value["text"]) lbl_value["text"]
= f"{value + 1}“
btn_increase = tk.Button(master=window,
text="+", command=increase)
Set value
Method 1
e3=Entry()
e3.insert(0,str(result))
Method 2
v=StringVar()
e3=Entry(textvariable=v)
v.set(str(result))
Method 3
l3=Label()
l3.configure(text="Result:")
Set background Color of Window
root=Tk()
root.configure(bg=“cyan”)
Support other format Images
Pip install pillow

from PIL import ImageTk,Image

img1=ImageTk.PhotoImage(Image.open('i2.gif'))
l=Label(root,image=img1,width=600,height=400)
Open New Window
# Import required libraries
from tkinter import *
# Create an instance of tkinter window
win = Tk()
win.geometry("700x400")
win.title("Root Window")
# Function to create a toplevel window
def create_top():
top=Toplevel(win)
top.geometry("400x250")
top.title("Toplevel Window")
Label(top, text="Hello, Welcome to Tutorialspoint", font='Arial 15 bold').pack()
buttn=Button(top, text="Close", command=top.destroy)
buttn.pack()
# Create a button to open the toplevel window
b1=Button(text="new window",command=create_top)
b1.pack()
b2=Button(text="Close window",command=quit)
b2.pack()

You might also like