Unit 4 - 1 Tkinter
Unit 4 - 1 Tkinter
• 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.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.
• widget.pack(options)
• 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.
• 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.
• The user can choose one or more items from the list depending upon
the configuration.
• 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:
• 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.
• 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.
• 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