0% found this document useful (0 votes)
69 views30 pages

Tkinter GUI

The document discusses Tkinter GUI widgets in Python. It describes how to create a main window and add widgets like labels, buttons and frames. It explains different geometry managers and attributes of widgets like padding, fonts and relief. Methods like pack, grid and place are used to organize widgets.

Uploaded by

Sanket Patil
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
0% found this document useful (0 votes)
69 views30 pages

Tkinter GUI

The document discusses Tkinter GUI widgets in Python. It describes how to create a main window and add widgets like labels, buttons and frames. It explains different geometry managers and attributes of widgets like padding, fonts and relief. Methods like pack, grid and place are used to organize widgets.

Uploaded by

Sanket Patil
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
You are on page 1/ 30

Tkinter GUI

We saw how you could easily create the main window in just three easy
steps in the previous tutorial. Obviously, the main window alone is of no
use; if we want to create a useful GUI application, we need to add different
buttons & widgets. This is what I will be teaching in this tutorial. So without
any further ado, let's jump to the concepts:

 The Graphical user interface(GUI) is used by today's most commercially


popular computer operating systems and software programs. It's the kind
of interface that allows users to manipulate elements on the screen using a
mouse, a stylus, or even a finger.
 Widgets are the basic building blocks for graphical user interface (GUI)
applications. Each GUI component (e.g., buttons, labels) is a widget that is
placed somewhere within a user interface window or is displayed as an
independent window.
 Tkinter also offers access to the widgets' geometric configuration, which
can organize the widgets in the parent windows. There are mainly three
geometry manager classes.
1. pack() method: It organizes the widgets in blocks before placing them in
the parent widget.
2. grid() method: Before placing them in the parent widget, it organizes
the widgets in the grid (table-like structure).
3. place() method: It organizes the widgets by placing them on specific
positions directed by the programmer.

 In Python, almost every widget object has several attributes. Here, we’ll talk
about standard widget attributes, including cursors, reliefs, colors, and
fonts.
1. Tkinter Widget state: The state of the widget is defined by state
attributes. NORMAL, ACTIVE, and DISABLED are the values of the
attributes.
2. Tkinter Widget padding: padx and pady –these two attributes come under
the category of widget padding, and they are responsible for adding extra
horizontal and vertical space to the widget. The padx and pady attributes
add space between the buttons.
3. Tkinter Background colors: The background colors of widgets can be set
with the background attributes. It can be abbreviated to bg.
4. Width &Height: The width and height attributes set the width and height
of the widget.
5. Tkinter Fonts: For working with fonts, it has a font module. It has some
built-in fonts such as TkTooltipFont, TkDefaultFont.
6. Tkinter Cursors: The cursor in Tkinter is set with the cursor
7. Tkinter Reliefs: A relief is a border decoration. The possible values
are SUNKEN, RAISED, GROOVE, RIDGE, and FLAT.

Label, Geometry, Maxsize & Minsize |


Python Tkinter GUI
Label(): A Label is a Tkinter Widget class used to display text or an image.
The label is a widget that the user just views but does not interact with.

Geometry(): This method is used to set the dimensions of the Tkinter


window and is used to set the position of the main window on the user’s
desktop.
Minsize(): This method is used to set the minimum size of the Tkinter
window. Using this method user can set the window’s initialized size to its
minimum size and still be able to maximize and scale the window larger.
Maxsize(): This method is used to set the maximum size of the Tkinter
window, i.e., the maximum size a window can be expanded. Users will still
be able to shrink the size of the window to the minimum possible.
Now let's see how we can implement all the three methods discussed
above:

 Importing tkinter is the same as importing any other module in the Python
code. Note that the module's name in Python 2.x is ‘Tkinter’, and in Python
3.x, it is ‘tkinter’.
from tkinter import *

Copy

 To create the main window, Tkinter offers a method, ‘Tk.’ To change the
window's name, you can change the className to the desired one.

imaginary_tech_root = Tk()

Copy

 To set the dimensions of the Tkinter window and to set the position of the
main window on the user’s desktop, the geometry() function is used. As in
the example: the width is 644 pixels, and the height is 434 pixels, so that we
can write the function as geometry(644x434).

imaginary_tech_root.geometry("644x434")

Copy

 To set the minimum size of the Tkinter window, we use minsize() function,
and to set the maximum size of the Tkinter window, we use maxsize() As in
the example: minsize(300,100) depicts the minimum width and height of
the Tkinter window must be 300 pixels and 100 pixels respectively. In the
same way, maxsize(1200,988) depicts the maximum width, and the height
of the Tkinter window must be 1200 and 988, respectively. Note: We have
to put a comma between width and height, unlike the geometry()
function.

imaginary_tech_root.minsize(300,100)
imaginary_tech_root.maxsize(1200, 988)

Copy

 To call the Label widget, which is a child of the root widget. The keyword
parameter "text" specifies the text “Shakaib is a good boy, and this is his
GUI” to be shown:
shakaib = Label(text="Shakaib is a good boy and this is his
GUI")

Copy

 The pack method tells Tk to fit the size of the window to the given text.

shakaib.pack()

Copy

 There is a method known by the name mainloop(), which is used when your
application is ready to run. This is an infinite loop used to run the
application, wait for an event to occur, and process the event as long as the
window is not closed.

imaginary_tech_root.mainloop()

Frame In Tkinter | Python Tkinter GUI


 A Frame widget is a rectangular region on the screen that can be used as a
foundation class to implement complex widgets. This widget is very
important for the process of grouping and organizing other widgets in a
friendly way. It works like a container, which is responsible for arranging the
position of other widgets. We can use bg, relief, borderwidth, bd as the
attributes of the Frame widget. Some important attributes are discussed
below:
 bg: The normal background color displayed behind the label and indicator.
 relief: The type of the border of the frame. Its default value is set to
FLAT. We can set it to any other styles,
i.e., FLAT, RAISED, SUNKEN, GROOVE, RIDGE.
 borderwidth: TkinterLabel doesn't have any border by default. We need
to assign the borderwidth option to add a border around the Label widget
along with the relief option to be an option rather than flat to make visible.
 bd: The size of the border around the indicator. Default is 2 pixels.
from tkinter import *

Copy

 To create the main window, Tkinter offers a method, 'Tk'. To change the name of the
window, you can change the className to the desired one.

root = Tk()

Copy

 To set the dimensions of the Tkinter window and to set the position of the main
window on the user's desktop, the geometry() function is used. As in the example:
the width is 655 pixels, and the height is 333 pixels, so we can write the function
as geometry(655x333).

root.geometry("655x333")

Copy

 To take Frame variable as f1 and set the attributes- bg (background color) =


"grey", borderwidth(thickness of the Frame's border)=6, and relief=SUNKEN. Then
the Frame f1 must be packed.

f1 = Frame(root, bg="grey", borderwidth=6, relief=SUNKEN)


f1.pack(side=LEFT, fill="y")

Copy

 In the same way, another Frame f2 is taken, and the attributes are set to the Frame.

f2 = Frame(root, borderwidth=8, bg="grey", relief=SUNKEN)


f2.pack(side=TOP, fill="x")

Copy

 To call the Label widget, which is a child of the root widget. The keyword parameter
"text" specifies the text "Project Tkinter - Pycharm" to be shown, and the pack
method tells Tk to fit the size of the window to the given text where pady adds extra
space (i.e., 142 in this example) from the upper and lower portion of the Frame
widget.

l = Label(f1, text="Project Tkinter - Pycharm")


l.pack( pady=142)

Copy

 In the same way, another label is taken, and the attributes are set to the Label.

l = Label(f2, text="Welcome to sublime text",


font="Helvetica 16 bold", fg="red", pady=22)
l.pack()

Copy

 There is a method known by the name mainloop(), which is used when your
application is ready to run. This is an infinite loop used to run the application, wait
for an event to occur, and process the event as long as the window is not closed.

root.mainloop()

Packing Buttons In Tkinter | Python


Tkinter GUI
The Button widget is a standard Tkinter widget, which is used for various
kinds of buttons. A button is a widget that is designed for the user to
interact with (i.e., if a mouse click presses the button, some action might be
started). They can also contain text and images like labels. While labels can
display text in various fonts, a button can only display text in a single font.
The text of a button can span more than one line.

A Python function or method can be associated with a button. This function


or method will be executed if the button is pressed in some way. We can
use bd, bg, command, fg, text, image, relief, etc., as attributes of the Button
widget. Some important attributes are discussed below:

 bg: The normal background color displayed behind the label and indicator.
 relief: The type of the border of the frame. Its default value is set to
FLAT. We can set it to any other styles,
i.e., FLAT, RAISED, SUNKEN, GROOVE, RIDGE.
 bd: The size of the border in pixels. Default is 2 pixels.
 font: Text font to be used for the button’s label.
 image: Instead of text, Image to be displayed on the button.
 command: Function or method to be called when the button is
clicked. Note: we only have to write the function or method name in
the command attribute. We should not call the function in the
attribute (i.e., If the function is name(), we just have to
write command=name).

 Importing tkinter is the same as importing any other module in the Python code.
Note that the name of the module in Python 2.x is ‘Tkinter’, and in Python 3.x, it is
‘tkinter’.

from tkinter import *

Copy

 To create the main window, Tkinter offers a method, ‘Tk’. To change the name of the
window, you can change the className to the desired one.

root =Tk()

Copy

 To set the dimensions of the Tkinter window and to set the position of the main
window on the user’s desktop, the geometry() function is used. As in the example:
the width is 655 pixels, and height is 333 pixels, so we can write the function
as geometry(655x333).
root.geometry("655x333")

Copy

 To define a function using ‘def’ (i.e., here, two functions, hello() and name() are
defined) and use it in button attributes.

def hello():
print("Hello tkinter Buttons")

def name():
print("Name is harry")

Copy

 To take Frame variable as frame and set the attributes- bg (background color) =
“grey”, borderwidth(thickness of the Frame’s border)=6, and relief=SUNKEN. Then
the Frame frame must be packed (here, it is packed on the left side and north-west
corner).

frame = Frame(root, borderwidth=6, bg="grey", relief=SUNKEN)


frame.pack(side=LEFT, anchor="nw")

Copy

 To take the Button variable (here we take four Button variables b1, b2, b3 & b4) and
use attributes in the Button widget (i.e., for Button b1, the attributes are fg
(foreground color) = “red”, text= “Print now” and command= hello, such that when
the Button name showing as “Print now” is clicked it will call the hello() function
through the command “hello” attribute and it will print “Hello tkinter Buttons”.

b1 = Button(frame, fg="red", text="Print now",


command=hello)
b1.pack(side=LEFT, padx=23)
b2 = Button(frame, fg="red", text="Tell me name now",
command=name)
b2.pack(side=LEFT, padx=23)

b3 = Button(frame, fg="red", text="Print now")


b3.pack(side=LEFT, padx=23)

b4 = Button(frame, fg="red", text="Print now")


b4.pack(side=LEFT, padx=23)

Copy

 There is a method known by the name mainloop(), which is used when your
application is ready to run. This is an infinite loop used to run the application, wait
for an event, and process the event as long as the window is not closed.

root.mainloop()

Entry Widget & Grid Layout In Tkinter |


Python Tkinter GUI Tutorial In Hindi
#10
 Entry() widgets are the basic widgets of Tkinter, which is used to get input,
i.e., text strings, from the user of an application. This widget allows the user
to enter a single line of text.

Note: If the user enters a string, which is longer than the available
display space of the widget, the content will be scrolled. This means
that the string cannot be seen in its entirety. The arrow keys can be used to
move to the invisible parts of the string. If you want to enter multiple
lines of text, you have to use the text widget. An entry widget is also
limited to a single font.
 The Grid() manager is the most flexible of the geometry managers in
Tkinter. The Grid() geometry manager puts the widgets in a 2-dimensional
table. The master widget is split into a number of rows and columns, and
each "cell" in the resulting table can hold a widget.

Note: We can also create layouts using Pack() manager, but it takes a
number of extra frame widgets and a lot of work to make things look good.
If you use the grid manager instead, you only need one call per widget to
get everything laid out properly.

Code is described below:

from tkinter import *

def getvals():
print(f"The value of username is {uservalue.get()}")
print(f"The value of password is {passvalue.get()}")

root = Tk()
root.geometry("655x333")

user = Label(root, text="Username")


password = Label(root, text="Password")
user.grid()
password.grid(row=1)

# Variable classes in tkinter


# BooleanVar, DoubleVar, IntVar, StringVar

uservalue = StringVar()
passvalue = StringVar()

userentry = Entry(root, textvariable = uservalue)


passentry = Entry(root, textvariable = passvalue)

userentry.grid(row=0, column=1)
passentry.grid(row=1, column=1)

Button(text="Submit", command=getvals).grid()

root.mainloop()

Travel Form Using Checkbuttons &


Entry Widget | Python Tkinter GUI
Tutorial In Hindi #11
In this tutorial, we'll make a Travel form using Label, Button, CheckButton
and Entry widgets, and grid() method. The title of the form is created using
the Label() widget. Different text sections are made with the Label() and are
appropriately placed using the grid() method. The inputs for the entry
sections are defined, and entry sections are created using the Entry() widget
and placed using the grid() method.

Code is described below:

from tkinter import *

root = Tk()

def getvals():
print("It works!")
root.geometry("644x344")
#Heading
Label(root, text="Welcome to Sanvee Travels",
font="comicsansms 13 bold", pady=15).grid(row=0, column=3)

#Text for our form


name = Label(root, text="Name")
phone = Label(root, text="Phone")
gender = Label(root, text="Gender")
emergency = Label(root, text="Emergency Contact")
paymentmode = Label(root, text="Payment Mode")

#Pack text for our form


name.grid(row=1, column=2)
phone.grid(row=2, column=2)
gender.grid(row=3, column=2)
emergency.grid(row=4, column=2)
paymentmode.grid(row=5, column=2)

# Tkinter variable for storing entries


namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
emergencyvalue = StringVar()
paymentmodevalue = StringVar()
foodservicevalue = IntVar()

#Entries for our form


nameentry = Entry(root, textvariable=namevalue)
phoneentry = Entry(root, textvariable=phonevalue)
genderentry = Entry(root, textvariable=gendervalue)
emergencyentry = Entry(root, textvariable=emergencyvalue)
paymentmodeentry = Entry(root,
textvariable=paymentmodevalue)

# Packing the Entries


nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
emergencyentry.grid(row=4, column=3)
paymentmodeentry.grid(row=5, column=3)

#Checkbox & Packing it


foodservice = Checkbutton(text="Want to prebook your
meals?", variable = foodservicevalue)
foodservice.grid(row=6, column=3)

#Button & packing it and assigning it a command


Button(text="Submit to Harry Travels",
command=getvals).grid(row=7, column=3)

root.mainloop()

Accepting User Input In Tkinter Form |


Python Tkinter GUI Tutorial In Hindi
#12
In this tutorial, we’ll make a form and learn how to accept user input in the
Tkinter form. We’ll also learn how to open a text (.txt) file and write or
append those input values in that file.

Code is described below:

from tkinter import *

root = Tk()

def getvals():
print("Submitting form")

print(f"{namevalue.get(), phonevalue.get(),
gendervalue.get(), emergencyvalue.get(),
paymentmodevalue.get(), foodservicevalue.get()} ")

with open("records.txt", "a") as f:


f.write(f"{namevalue.get(), phonevalue.get(),
gendervalue.get(), emergencyvalue.get(),
paymentmodevalue.get(), foodservicevalue.get()}\n ")

root.geometry("644x344")
#Heading
Label(root, text="Welcome to Harry Travels",
font="comicsansms 13 bold", pady=15).grid(row=0, column=3)

#Text for our form


name = Label(root, text="Name")
phone = Label(root, text="Phone")
gender = Label(root, text="Gender")
emergency = Label(root, text="Emergency Contact")
paymentmode = Label(root, text="Payment Mode")

#Pack text for our form


name.grid(row=1, column=2)
phone.grid(row=2, column=2)
gender.grid(row=3, column=2)
emergency.grid(row=4, column=2)
paymentmode.grid(row=5, column=2)

# Tkinter variable for storing entries


namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
emergencyvalue = StringVar()
paymentmodevalue = StringVar()
foodservicevalue = IntVar()

#Entries for our form


nameentry = Entry(root, textvariable=namevalue)
phoneentry = Entry(root, textvariable=phonevalue)
genderentry = Entry(root, textvariable=gendervalue)
emergencyentry = Entry(root, textvariable=emergencyvalue)
paymentmodeentry = Entry(root,
textvariable=paymentmodevalue)

# Packing the Entries


nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
emergencyentry.grid(row=4, column=3)
paymentmodeentry.grid(row=5, column=3)

#Checkbox & Packing it


foodservice = Checkbutton(text="Want to prebook your
meals?", variable = foodservicevalue)
foodservice.grid(row=6, column=3)

#Button & packing it and assigning it a command


Button(text="Submit to Harry Travels",
command=getvals).grid(row=7, column=3)

root.mainloop()

Handling Events In Tkinter GUI | Python


Tkinter GUI Tutorial In Hindi #14
Tkinter is a GUI (Graphical User Interface) module that is widely used in desktop
applications. It provides a variety of Widget classes and functions, with the help of
which one can make our GUI more attractive and user-friendly in terms of both looks
and functionality. The binding function is used to deal with the events. We can
bind Python’s Functions and methods to an event and bind these functions to any
particular widget. Events can come from various sources, including key presses and
mouse operations by the user and redraw events from the window manager
(indirectly caused by the user, in many cases).
The most important part of an event specifier is the type field. It specifies the kind of
event that we wish to bind and can be user actions like Button and Key, or window
managers events like Enter, Configure, and others.
Event formats:

 <Button-1>: A mouse button is pressed over the widget. Button 1 is the leftmost button,
Button 2 is the middle button (where available), and Button 3 is the rightmost button.
 <B1-Motion>: The mouse is moved, with mouse button 1 being held down (use B2 for the
middle button, B3 for the right button).
 <Double-Button-1>: Button 1 was double-clicked. You can use Double or Triple as
prefixes. Note: Both bindings will be called if you bind to both a single click (<Button-
1>) and a double click.
 <Enter>: The mouse pointer entered the widget. Note: This event doesn’t mean that the
user pressed the Enter key.

Event attributes:

As Event attributes, we can use width, height, char, num, widget, etc.

Code is described below:

from tkinter import *

def harry(event):
print(f"You clicked on the button at {event.x},
{event.y}")

root = Tk()
root.title("Events in Tkinter")
root.geometry("644x334")

widget = Button(root, text='Click me please')


widget.pack()

widget.bind('<Button-1>', harry)
widget.bind('<Double-1>', quit)
root.mainloop()

Copy
Menus & Submenus In Tkinter Python |
Python Tkinter GUI Tutorial In Hindi #17
The Menu widget is used to implement different types of menus (toplevel, pulldown,
and popup menus). The goal of this widget is to allow us to create all kinds of menus
that can be used by our applications. It is also possible to use other extended
widgets to implement new types of menus, such as the OptionMenu widget, which
implements a special type that generates a pop-up list of items within a selection.

Attributes:

 bg: The background color for choices not under the mouse.
 bd: The width of the border around all the choices. Default is 1.
 fg: The foreground color used for choices not under the mouse.
 tearoff: Normally, a menu can be torn off. The first position (position 0) in the list of choices
is occupied by the tear-off element and the additional choices are added starting at position
1. If you set tearoff=0, the menu will not have a tear-off feature and choices will be added
starting at position 0.
 relief: The default 3-D effect for menus is relief=RAISED.
 title: Normally, the title of a tear-off menu window will be the same as the text of the
menubutton or cascade that lead to this menu. If you want to change the title of that
window, set the title option to that string.

Code is described below:

from tkinter import *


root = Tk()
root.geometry("733x566")
root.title("Pycharm")

def myfunc():
print("Mai ek bahut hi natkhat aur shaitaan function
hoon")

# #Use these to create a non dropdown menu


# mymenu = Menu(root)
# mymenu.add_command(label="File", command=myfunc)
# mymenu.add_command(label="Exit", command=quit)
# root.config(menu=mymenu)

mainmenu = Menu(root)

m1 = Menu(mainmenu, tearoff=0)
m1.add_command(label="New project", command=myfunc)
m1.add_command(label="Save", command=myfunc)
m1.add_separator()
m1.add_command(label="Save As", command=myfunc)
m1.add_command(label="Print", command=myfunc)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="File", menu=m1)

m2 = Menu(mainmenu, tearoff=0)
m2.add_command(label="Cut", command=myfunc)
m2.add_command(label="Copy", command=myfunc)
m2.add_separator()
m2.add_command(label="Paste", command=myfunc)
m2.add_command(label="Find", command=myfunc)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="Edit", menu=m2)

root.mainloop()

Copy

Message Box In Tkinter Python | Python


Tkinter GUI Tutorial In Hindi #18
Python Tkinter-MessageBox module is used to display the message boxes in the
python applications. This module provides a number of functions that a user can use
to display an appropriate message. Some of these functions are showinfo,
askquestion, showwarning, showerror, askokcancel, askyesno, and askretrycancel.

Parameters:

tmsg.Function_Name(title, message [, options])

Copy

 tmsg is used to defining TKMessageBox. For this, we have to import tkinter.messagebox as


tmsg.
 Function_Name: This is the name of the appropriate message box
function.
 title: This is the text to be displayed in the title bar of a message box.
 message: This is the text to be displayed as a message in the message
box.
 options: Options are alternative choices that may be used to tailor a
standard message box.

1. default: The default option is used to specify the default button, such as
ABORT, RETRY, or IGNORE, in the message box.
2. parent: The parent option is used to specify the window on top of which
the message box is to be displayed.

Code is described below:

from tkinter import *


import tkinter.messagebox as tmsg
root = Tk()
root.geometry("733x566")
root.title("Pycharm")

def myfunc():
print("Mai ek bahut hi natkhat aur shaitaan function
hoon")

def help():
print("I will help you")
tmsg.showinfo("Help", "Sanvee
will help you with this gui")

def rate():
print("Rate us")
value = tmsg.askquestion("Was your experience Good?",
"You used this gui.. Was your experience
Good?")
if value == "yes":
msg = "Great. Rate us on appstore please"
else:
msg = "Tell us what went wrong. We will call you
soon"
tmsg.showinfo("Experience", msg)

def divya():
ans = tmsg.askretrycancel("Divya se dosti kar lo",
"Sorry divya nahi banegi aapki dost")
if ans:
print("Retry karne pe bhi kuch nahi hoga")

else:
print("Bahut badiya bhai cancel kar diya warna
pitte")

mainmenu = Menu(root)

m1 = Menu(mainmenu, tearoff=0)
m1.add_command(label="New project", command=myfunc)
m1.add_command(label="Save", command=myfunc)
m1.add_separator()
m1.add_command(label="Save As", command=myfunc)
m1.add_command(label="Print", command=myfunc)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="File", menu=m1)

m2 = Menu(mainmenu, tearoff=0)
m2.add_command(label="Cut", command=myfunc)
m2.add_command(label="Copy", command=myfunc)
m2.add_separator()
m2.add_command(label="Paste", command=myfunc)
m2.add_command(label="Find", command=myfunc)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="Edit", menu=m2)

m3 = Menu(mainmenu, tearoff=0)
m3.add_command(label = "Help", command=help)
m3.add_command(label = "Rate us", command=rate)
m3.add_command(label = "Befriend Divya", command=divya)
mainmenu.add_cascade(label="Help", menu=m3)
root.config(menu=mainmenu)
root.mainloop()

Copy

The Listbox() widget is a standard Tkinter widget that displays a list of items from
which a user can select a number of items. The Listbox can only contain text items,
and all items must have the same font and color. Depending on the widget
configuration, the user can choose one or more alternatives from the list.
Listboxes are used to select from a group of textual items. Depending on how the
Listbox is configured, the user can select one or many items from that list.
Attributes:

 bg: It is used to set the background color of the widget.


 fg: It is used to set the color of the text.
 bd: It represents the size of the border. The default value is 2 pixels.
 font: It sets the font type of the Listbox items (the font type of all Listbox items will be the
same).

Methods:

 activate(index): It is used to select the lines at the specified index.


 delete(first, last = None): It is used to delete the lines which exist in the given range.
 insert(index, *elements): It is used to insert the new lines with the specified number of
elements before the specified index.
 get(first, last = None): It is used to get the list of items that exist in the given range.
 index(i): It is used to place the line with the specified index at the top of the widget.

Code is described below:

from tkinter import *

def add():
global i
lbx.insert(ACTIVE, f"{i}")
i+=1

i = 0
root = Tk()
root.geometry("455x233")
root.title("Listbox tutorial")

lbx = Listbox(root)
lbx.pack()
lbx.insert(END, "First item of our listbox")

Button(root, text="Add Item", command=add).pack()


root.mainloop()

ScrollBar In Tkinter GUI | Python Tkinter


GUI Tutorial In Hindi #22
The Scrollbar () widget provides a slide controller used to implement vertically
scrolled widgets, such as Listbox, Text, and Canvas. Horizontal scrollbars can also be
used with the Entry widget.
To connect a vertical scrollbar to such a widget, you have to do two things:

 Set the widget’s yscrollcommand callbacks to the set method of the Scrollbar.

widget(yscrollcommand = scrollbar.set)

Copy

 Set the Scrollbar’s command to the yview method of the widget using config().

scrollbar.config(command=widget.yview)

Copy

Attributes:

 bg: It is used to set the color of the slider and arrowheads when the mouse is not over them.
 bd: The width of the 3-d borders around the trough’s entire perimeter and the width of the
3-d affects the arrowheads and slider. Default is no border around the trough and a 2-pixel
border around the arrowheads and slider.
 orient: It is used to set orient=HORIZONTAL for a horizontal scrollbar, orient=VERTICAL for
a vertical one.
 width: It sets the width of the Scrollbar (its y dimension if horizontal, and its x dimension if
vertical). Default is 16.
Code is described below:

from tkinter import *


root = Tk()
root.geometry("455x233")
root.title("Scrollbar tutorial")
# For connecting scrollbar to a widget
# 1. widget(yscrollcommand = scrollbar.set)
# 2 scrollbar.config(command=widget.yview)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(root, yscrollcommand = scrollbar.set)


for i in range(344):
listbox.insert(END, f"Item {i}")

listbox.pack(fill="both",padx=22)
#text = Text(root, yscrollcommand = scrollbar.set)
#text.pack(fill=BOTH)
scrollbar.config(command=listbox.yview)
#scrollbar.config(command=text.yview)

root.mainloop()

Copy

Creating a GUI Notepad In Tkinter |


Python Tkinter GUI Tutorial In Hindi
#29
Code as described/written in the video
from tkinter import *
from tkinter.messagebox import showinfo
from tkinter.filedialog import askopenfilename,
asksaveasfilename
import os

def newFile():
global file
root.title("Untitled - Notepad")
file = None
TextArea.delete(1.0, END)

def openFile():
global file
file = askopenfilename(defaultextension=".txt",
filetypes=[("All Files", "*.*"),
("Text Documents",
"*.txt")])
if file == "":
file = None
else:
root.title(os.path.basename(file) + " - Notepad")
TextArea.delete(1.0, END)
f = open(file, "r")
TextArea.insert(1.0, f.read())
f.close()

def saveFile():
global file
if file == None:
file = asksaveasfilename(initialfile =
'Untitled.txt', defaultextension=".txt",
filetypes=[("All Files", "*.*"),
("Text Documents",
"*.txt")])
if file =="":
file = None

else:
#Save as a new file
f = open(file, "w")
f.write(TextArea.get(1.0, END))
f.close()

root.title(os.path.basename(file) + " -
Notepad")
print("File Saved")
else:
# Save the file
f = open(file, "w")
f.write(TextArea.get(1.0, END))
f.close()

def quitApp():
root.destroy()

def cut():
TextArea.event_generate(("<>"))
def copy():
TextArea.event_generate(("<>"))

def paste():
TextArea.event_generate(("<>"))

def about():
showinfo("Notepad", "Notepad by Code With Harry")

if __name__ == '__main__':
#Basic tkinter setup
root = Tk()
root.title("Untitled - Notepad")
root.wm_iconbitmap("1.ico")
root.geometry("644x788")

#Add TextArea
TextArea = Text(root, font="lucida 13")
file = None
TextArea.pack(expand=True, fill=BOTH)

# Lets create a menubar


MenuBar = Menu(root)

#File Menu Starts


FileMenu = Menu(MenuBar, tearoff=0)
# To open new file
FileMenu.add_command(label="New", command=newFile)
#To Open already existing file
FileMenu.add_command(label="Open", command = openFile)

# To save the current file

FileMenu.add_command(label = "Save", command = saveFile)


FileMenu.add_separator()
FileMenu.add_command(label = "Exit", command = quitApp)
MenuBar.add_cascade(label = "File", menu=FileMenu)
# File Menu ends

# Edit Menu Starts


EditMenu = Menu(MenuBar, tearoff=0)
#To give a feature of cut, copy and paste
EditMenu.add_command(label = "Cut", command=cut)
EditMenu.add_command(label = "Copy", command=copy)
EditMenu.add_command(label = "Paste", command=paste)

MenuBar.add_cascade(label="Edit", menu = EditMenu)

# Edit Menu Ends

# Help Menu Starts


HelpMenu = Menu(MenuBar, tearoff=0)
HelpMenu.add_command(label = "About Notepad",
command=about)
MenuBar.add_cascade(label="Help", menu=HelpMenu)

# Help Menu Ends


root.config(menu=MenuBar)

#Adding Scrollbar using rules from Tkinter lecture no 22


Scroll = Scrollbar(TextArea)
Scroll.pack(side=RIGHT, fill=Y)
Scroll.config(command=TextArea.yview)
TextArea.config(yscrollcommand=Scroll.set)

root.mainloop()

You might also like