0% found this document useful (0 votes)
19 views88 pages

Unit 4 - 1 Tkinter

Uploaded by

Nitin bhainsora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views88 pages

Unit 4 - 1 Tkinter

Uploaded by

Nitin bhainsora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Tkinter

Dr. Neetu Narwal


Tkinter
• 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.
• 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 quickly build something
that’s functional and cross-platform.
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.
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 be while still fully encompassing the widget. Now
execute the following:

• >>> window.mainloop()
• Nothing seems to happen, but notice that no new prompt appears in
the shell.

• 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 you close the
window where you called the method. Go ahead and close the window
you’ve created, and you’ll see a new prompt displayed in the shell.
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.

• The pack() method


• The grid() method
• 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.
• However, the controls are less and widgets are generally added in the less
organized manner.

• widget.pack(options)

• A list of possible options that can be passed in pack() is given below.


• expand: If the expand is set to true, the widget expands to fill any space.
• Fill: By default, the fill is set to NONE. However, we can set it to X or Y to
determine whether the widget contains any extra space.
• size: it represents the side of the parent to which the widget is to be placed on
the window.
• Example
• # !/usr/bin/python3
• 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.
widget.grid(options)
• A list of possible options that can be passed inside the grid() method is given
below.
• Column : The column number in which the widget is to be placed. The
leftmost column is represented by 0.
• Columnspan : The width of the widget. It represents the number of columns
up to which, the column is expanded.
• ipadx, ipady : It represents the number of pixels to pad the widget inside the
widget's border.
• padx, pady : It represents the number of pixels to pad the widget
outside the widget's border.
• row : The row number in which the widget is to be placed. The
topmost row is represented by 0.
• rowspan : The height of the widget, i.e. the number of the row up to
which the widget is expanded.
• Sticky : If the cell is larger than a widget, then sticky is used to
specify the position of the widget inside the cell. It may be the
concatenation of the sticky letters representing the position of the
widget. It may be N, E, W, S, NE, NW, NS, EW, ES.
• # !/usr/bin/python3
• 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 = 4, column = 0)
• parent.mainloop()
Introduction to the Tkinter grid geometry manager
• The grid geometry manager uses the concepts of rows and
columns to arrange the widgets.
• The following shows a grid that consists of four rows and three
columns:
• The intersection of a row and a column is called a cell. A cell is an area
where you can place a widget. A cell can hold only one widget. If you
place two widgets in a cell, they’ll be on top of each other.

• To place multiple widgets in a cell, you use a Frame or LabelFrame to


wrap the widgets and place the Frame or LabelFrame on the cell.

• The width of a column depends on the width of the widget it contains.


Similarly, the height of a row depends on the height of the widgets
contained within the row.

• Rows and columns can span. The following illustrates a grid that has
the cell (1,1) that spans two columns and the cell (0,2) that spans two
rows:
Python Tkinter place() method
• The place() geometry manager organizes the widgets to the specific x
and y coordinates.
• widget.place(options)
• A list of possible options is given below.
• Anchor: It represents the exact position of the widget within the
container. The default value (direction) is NW (the upper left corner)
• bordermode: The default value of the border type is INSIDE that refers
to ignore the parent's inside the border. The other option is OUTSIDE.
• height, width: It refers to the height and width in pixels.
• relheight, relwidth: It is represented as the float between 0.0 and 1.0
indicating the fraction of the parent's height and width.
• relx, rely: It is represented as the float between 0.0 and 1.0 that is the
offset in the horizontal and vertical direction.
• x, y: It refers to the horizontal and vertical offset in the pixels.
• Example
• # !/usr/bin/python3
• 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 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.
• Syntax
• w = Entry (parent, options)
• # !/usr/bin/python3
• 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)
• 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()
• Example: A simple calculator
• 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)
• abelNum2 = 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 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.

• 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()
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.
• W = Button(parent, options)
• from tkinter import *
• parent = Tk()
• parent.geometry("200x100")
• b = Button(parent, text = "Simple")
• b.pack()
• parent.mainaloop()
• from tkinter import *
• parent = Tk()
• parent.geometry("200x100")
• def fun():
• messagebox.showinfo("Hello", "Red Button clicked")
• b1 = Button(parent,text = "Red",command = fun,activeforeground =
"red",activebackground = "pink", pady=10)
• b2 = Button(parent, text = "Blue",activeforeground = "blue",activebackground =
"pink",pady=10)
• b3 = Button(parent, text = "Green",activeforeground = "green",activebackground =
"pink",pady = 10)
• b4 = Button(parent, text = "Yellow",activeforeground = "yellow",activebackground =
"pink",pady = 10)
• b1.pack(side = LEFT)
• b2.pack(side = RIGHT)
• b3.pack(side = TOP)
• b4.pack(side = BOTTOM)
• parent.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.
• Syntax
• w = checkbutton(master, options)
• Example
• from tkinter import *
• top = Tk()
• top.geometry("200x200")
• checkvar1 = IntVar()
• checkvar2 = IntVar()
• checkvar3 = IntVar()
• chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1, onvalue = 1,
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()
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
1.w = Radiobutton(top, options)
1. from tkinter import *
2.
3. def selection():
4. selection = "You selected the option " + str(radio.get())
5. label.config(text = selection)
6.
7. parent = Tk()
8. parent.geometry("300x150")
9. radio = IntVar()
10.lbl = Label(text = "Favourite programming language:")
11.lbl.pack()
12.R1 = Radiobutton(top, text="C", variable=radio, value=1, command=selection)
13.R1.pack( anchor = W )
14.
15.R2 = Radiobutton(top, text="C++", variable=radio, value=2, command=selection)
16.R2.pack( anchor = W )
17.
18.R3 = Radiobutton(top, text="Java", variable=radio, value=3, command=selection)
19.R3.pack( anchor = W)
20. label = Label(top)
21.label.pack()
22.top.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, "Australia")

• lbl.pack()
• listbox.pack()

• top.mainloop()
• 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 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.

• 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()
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.
• Syntax
messagebox.function_name(title, message [, options])
• Parameters
• function_name: It represents an appropriate message box function.
• title: It is a string which is shown as a title of a message box.
• message: It is the string to be displayed as a message on the message box.
• options: There are various options which can be used to configure the message dialog
box.
• The two options that can be used are default and parent.
• 1. default
• The default option is used to mention the types of the default button, i.e. ABORT, RETRY,
or IGNORE in the message box.
• 2. parent
• The parent option specifies the parent window on top of which, the message box is to be
displayed.
• here is one of the following functions used to show the appropriate message
boxes. All the functions are used with the same syntax but have the specific
functionalities.
• 1. showinfo()
• The showinfo() messagebox is used where we need to show some relevant
information to the user.
• Example
1.# !/usr/bin/python3
2. from tkinter import *
3. from tkinter import messagebox
4. top = Tk()
5. top.geometry("100x100")
6. messagebox.showinfo("information","Information")
7.
8.top.mainloop()
• 2. showwarning()
• This method is used to display the warning to the user. Consider the
following example.
• Example
1.# !/usr/bin/python3
2.from tkinter import *
3. from tkinter import messagebox
4. top = Tk()
5.top.geometry("100x100")
6.messagebox.showwarning("warning","Warning")
7. top.mainloop()
• 3. showerror()
• This method is used to display the error message to the user.
Consider the following example.
• Example
1.# !/usr/bin/python3
2.from tkinter import *
3.from tkinter import messagebox
4. top = Tk()
5.top.geometry("100x100")
6.messagebox.showerror("error","Error")
7.top.mainloop()
• 4. askquestion()
• This method is used to ask some question to the user which can be
answered in yes or no. Consider the following example.
• Example
1.# !/usr/bin/python3
2.from tkinter import *
3.from tkinter import messagebox
4. top = Tk()
5.top.geometry("100x100")
6.messagebox.askquestion("Confirm","Are you sure?")
7.top.mainloop()
• 5. askokcancel()
• This method is used to confirm the user's action regarding some
application activity. Consider the following example.
• Example
• # !/usr/bin/python3
• from tkinter import *
• from tkinter import messagebox
• top = Tk()
• top.geometry("100x100")
• messagebox.askokcancel("Redirect","Redirecting you to
www.javatpoint.com")
• top.mainloop()
• 6. 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.
• Example
1.# !/usr/bin/python3
2.from tkinter import *
3.from tkinter import messagebox
4. top = Tk()
5.top.geometry("100x100")
6.messagebox.askyesno("Application","Got It?")
7.top.mainloop()
• 7. askretrycancel()
• This method is used to ask the user about doing a particular task again or
not. Consider the following example.
• Example
1.# !/usr/bin/python3
2.from tkinter import *
3.from tkinter import messagebox
4.
5.top = Tk()
6.top.geometry("100x100")
7.messagebox.askretrycancel("Application","try again?")
8.
9.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)
1.from tkinter import *
2.
3.top = Tk()
4.top.geometry("100x100")
5.var = StringVar()
6.msg = Message( top, text = "Welcome to Javatpoint")
7. msg.pack()
8.top.mainloop()
Introduction to Tkinter Place Geometry
Manager
• The Tkinter place geometry manager allows you to specify the exact placement of a widget
using either absolution or relative positioning.

• The placer geometry management gives you fine control over the positioning of widgets by
allowing you to:
• Specify coordinates (x, y).
• Use relative positioning based on anchor points.

• To use the place geometry manager, you call the place() method on the widget like this:
• widget.place(**options)
• 1) Absolute positioning
• In absolute positioning, you specify the exact x and y coordinates of the widget using the x
and y parameters:
• widget.place(x=50, y=50)
• For example, the following place the widget in the center of its parent:
• widget.place(relx=0.5, rely=0.5, anchor=CENTER)
• 3) width and height
• The place geometry manager allows you to set the width and height of the
widget via the width and height paramaters:

• widget.place(width=120, height=60)
• Alternatively, you can use relative sizing concerning the parent container. For
example, the following code sets the widget’s width and height to 50% of the
parent’s dimensions:

• widget.place(relwidth=0.5, relheight=0.5)
• The relwidth and relheight has a value of a floating-point number between 0.0
and 1.0. This value represents a fraction of the width and height of the parent
container.
• 4) Anchor
• The anchor parameter determines which part of the widget is
positioned at the given coordinates.
• The anchor parameter accepts values such as:
• 'n', 'ne', 'e', 'se', 'sw', 'w', 'nw': These constants represent the cardinal and
intercardinal directions (north, northeast, east, southeast, south,
southwest, west, northwest).
• 'center': This value instructs the place() method to position the center
of the widget at the specified coordinates.
• The default value of the anchor is 'nw' which instructs the place()
method to position the top left of the widget at the specified
coordinates.
• For example, the following code places the widget in the center of the
container widget:

• widget.place(relx=0.5, rely=0.5, anchor='center')


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)
• from tkinter import *
• top = Tk()
• top.geometry("200x200")
• #creating a simple canvas
• c = Canvas(top,bg = "pink",height = "200")
• c.pack()
• top.mainloop()
Example: Creating an arc
• 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()
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)
• Creating a top level menu
1.from tkinter import *
2. top = Tk()
3.def hello():
4. print("hello!")
5.
6.# create a toplevel menu
7.menubar = Menu(root)
8.menubar.add_command(label="Hello!", command=hello)
9.menubar.add_command(label="Quit!", command=top.quit)
10.
11.# display the menu
12.top.config(menu=menubar)
13.
14.top.mainloop()
1.from tkinter import Toplevel, Button, Tk, Menu
2. top = Tk()
3.menubar = Menu(top)
4.file = Menu(menubar, tearoff=0)
5.file.add_command(label="New")
6.file.add_command(label="Open")
7.file.add_command(label="Save")
8.file.add_command(label="Save as...")
9.file.add_command(label="Close")
10.file.add_separator()
11.file.add_command(label="Exit", command=top.quit)
1.menubar.add_cascade(label="File", menu=file)
2.edit = Menu(menubar, tearoff=0)
3.edit.add_command(label="Undo")
4.edit.add_separator()
5.edit.add_command(label="Cut")
6.edit.add_command(label="Copy")
7.edit.add_command(label="Paste")
8.edit.add_command(label="Delete")
9.edit.add_command(label="Select All")
10. menubar.add_cascade(label="Edit", menu=edit)
11.help = Menu(menubar, tearoff=0)
12.help.add_command(label="About")
13.menubar.add_cascade(label="Help", menu=help)
14.top.config(menu=menubar)
15.top.mainloop()
End

You might also like