2024 Gui Pythontkinter Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

This file has 1. GUI tkinter notes 2. Code for username and password 3.

Code for date validation

Python Tkinter notes

Tkinter is the most commonly used library for developing GUI (Graphical User Interface) in Python. It is
a standard Python interface to the Tk GUI toolkit shipped with Python. As Tk and Tkinter are available on
most of the Unix platforms as well as on the Windows system, developing GUI applications with Tkinter
becomes the fastest and easiest.

Fundamental structure of tkinter program :

Syntax :
import tkinter
(Or)
from tkinter import *

There are two main methods used while creating the Python application with GUI.
1. Tk(screenName=None, baseName=None, className=’Tk’, useTk=1):
To create a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None,
className=’Tk’, useTk=1)’.
To change the name of the window, you can change the className to the desired one. The basic
code used to create the main window of the application is:

m=tkinter.Tk( ) where m is the name of the main window object

2. mainloop(): There is a method known by the name mainloop() is used when your application is ready
to run. mainloop() 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.

m.mainloop( )

import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()
What are Widgets?

Widgets in Tkinter are the elements of GUI application which provides various controls (such as Labels,
Buttons, ComboBoxes, CheckBoxes, MenuBars, RadioButtons and many more) to users to interact with
the application.

There are a number of widgets which you can put in your tkinter application. Some of the major widgets
are explained below:
1. Button: To add a button in your application, this widget is used.
The general syntax is:

w=Button(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the Buttons. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 activebackground: to set the background color when button is under the cursor.
 activeforeground: to set the foreground color when button is under the cursor.
 bg: to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the button.
 width: to set the width of the button.
 height: to set the height of the button.

#Example:

import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()

Output:

2. Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.
The general syntax is:
w = Canvas(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used in the canvas.
 highlightcolor: to set the color shown in the focus highlight.
 width: to set the width of the widget.
 height: to set the height of the widget.

#Example:

from tkinter import *


master = Tk()
w = Canvas(master, width=40, height=60)
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()

Output:

3. CheckButton: To select any number of options by displaying a number of options to a user as toggle
buttons. The general syntax is:
w = CheckButton(master, option=value)
There are number of options which are used to change the format of this widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 Title: To set the title of the widget.
 activebackground: to set the background color when widget is under the cursor.
 activeforeground: to set the foreground color when widget is under the cursor.
 bg: to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.

#Example:

from tkinter import *


master = Tk()
var1 = IntVar()
Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)
mainloop()

Output:
4. Entry:It is used to input the single line text entry from the user.. For multi-line text input, Text widget
is used.
The general syntax is:

w=Entry(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used.
 command: to call a function.
 highlightcolor: to set the color shown in the focus highlight.
 width: to set the width of the button.
 height: to set the height of the button.

#Example:

from tkinter import *


master = Tk()
Label(master, text='First Name').grid(row=0)
Label(master, text='Last Name').grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop()

Output:

5.Frame: It acts as a container to hold the widgets. It is used for grouping and organizing the widgets.
The general syntax is:
w = Frame(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 highlightcolor: To set the color of the focus highlight when widget has to be focused.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used.
 width: to set the width of the widget.
 height: to set the height of the widget.

#Example:
from tkinter import *

root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'RED', fg ='red')
redbutton.pack( side = LEFT)
brownbutton = Button(frame, text = 'BROWN', fg='brown')
brownbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='BLUE', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='BLACK', fg ='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()

Output:

6. Label: It refers to the display box where you can put any text or image which can be updated any time as
per the code.
The general syntax is:
w=Label(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 bg: to set he normal background color.
 bg to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the button.
 width: to set the width of the button.
 height” to set the height of the button.

#Example:

from tkinter import *


root = Tk()
w = Label(root, text='CHETTINAD VIDYASHRAM')
w.pack()
root.mainloop()
OUTPUT:

7. Listbox: It offers a list to the user from which the user can accept any number of options.
The general syntax is:
w = Listbox(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 highlightcolor: To set the color of the focus highlight when widget has to be focused.
 bg: to set he normal background color.
 bd: to set the border width in pixels.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.

#Example:
from tkinter import *

top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()
top.mainloop()

Output:

8.MenuButton: It is a part of top-down menu which stays on the window all the time. Every menubutton
has its own functionality. The general syntax is:
w = MenuButton(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 activebackground: To set the background when mouse is over the widget.
 activeforeground: To set the foreground when mouse is over the widget.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
 highlightcolor: To set the color of the focus highlight when widget has to be focused.

#Example:
from tkinter import *
top = Tk()
mb = Menubutton ( top, text = "GfG")
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
cVar = IntVar()
aVar = IntVar()
mb.menu.add_checkbutton ( label ='Contact', variable = cVar )
mb.menu.add_checkbutton ( label = 'About', variable = aVar )
mb.pack()
top.mainloop()

Output:

9.Menu: It is used to create all kinds of menus used by the application.


The general syntax is:
w = Menu(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of this widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 title: To set the title of the widget.
 activebackground: to set the background color when widget is under the cursor.
 activeforeground: to set the foreground color when widget is under the cursor.
 bg: to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
#Example:
from tkinter import *
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()

Output:

10. Message box: It refers to the multi-line and non-editable text. It works same as that of Label.
The general syntax is:

w = Message(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 bd: to set the border around the indicator.
 bg: to set he normal background color.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
#Example:
from tkinter import *
main = Tk()
ourMessage ='This is our Message'
messageVar = Message(main, text = ourMessage)
messageVar.config(bg='lightgreen')
messageVar.pack( )
main.mainloop( )
Output:

11. RadioButton: It is used to offer multi-choice option to the user. It offers several options to the user and
the user has to choose one option.
The general syntax is:
w = RadioButton(master, option=value)
There are number of options which are used to change the format of this widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 activebackground: to set the background color when widget is under the cursor.
 activeforeground: to set the foreground color when widget is under the cursor.
 bg: to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the label in characters.
 height: to set the height of the label in characters.
#Example:
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)
mainloop()
Output:

12. Scale: It is used to provide a graphical slider that allows to select any value from that scale. The general
syntax is:
w = Scale(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 cursor: To change the cursor pattern when the mouse is over the widget.
 activebackground: To set the background of the widget when mouse is over the widget.
 bg: to set he normal background color.
 orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
 from_: To set the value of one end of the scale range.
 to: To set the value of the other end of the scale range.
 image: to set the image on the widget.
 width: to set the width of the widget.

#Example:
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()

Output:

13. Scrollbar: It refers to the slide controller which will be used to implement listed widgets.
The general syntax is:
w = Scrollbar(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 width: to set the width of the widget.
 activebackground: To set the background when mouse is over the widget.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.

#Example:
from tkinter import *
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )
mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert(END, 'This is line number' + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()
Output:

14. Text: To edit a multi-line text and format the way it has to be displayed.
The general syntax is:
w =Text(master, option=value)
There are number of options which are used to change the format of the text. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 highlightcolor: To set the color of the focus highlight when widget has to be focused.
 insertbackground: To set the background of the widget.
 bg: to set he normal background color.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.

#Example:
from tkinter import *
root = Tk()
T = Text(root, height=2, width=30)
T.pack()
T.insert(END, 'BEST WISHES\n')
mainloop()

Output:

15. TopLevel: This widget is directly controlled by the window manager. It don’t need any parent
window to work on.The general syntax is:
w = TopLevel(master, option=value)
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 width: to set the width of the widget.
 height: to set the height of the widget.

#Example:
from tkinter import *
root = Tk()
root.title('GfG')
top = Toplevel()
top.title('Python')
top.mainloop()

Output:

16. SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of
numbers.The general syntax is:
w = SpinBox(master, option=value)
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 command: To call a function.
 width: to set the width of the widget.
 activebackground: To set the background when mouse is over the widget.
 disabledbackground: To disable the background when mouse is over the widget.
 from_: To set the value of one end of the range.
 to: To set the value of the other end of the range.

#Example:
from tkinter import *
master = Tk()
w = Spinbox(master, from_ = 0, to = 10)
w.pack()
mainloop()
Output:

17. PannedWindow:It is a container widget which is used to handle number of panes arranged in it. The
general syntax is:
w = PannedWindow(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 width: to set the width of the widget.
 height: to set the height of the widget.
#Example:
from tkinter import *
m1 = PanedWindow()
m1.pack(fill = BOTH, expand = 1)
left = Entry(m1, bd = 5)
m1.add(left)
m2 = PanedWindow(m1, orient = VERTICAL)
m1.add(m2)
top = Scale( m2, orient = HORIZONTAL)
m2.add(top)
mainloop()
Output:

DIFFERENT TYPES OF METHODS FOR CONFIGURING THE WIDGETS :

tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in
the parent windows. There are mainly three geometry manager classes class.
1. pack() method: It organizes the widgets in blocks before placing in the parent widget.
This geometry manager organizes widgets in blocks before placing them in the parent widget.
SYNTAX:
widget.pack( pack_options )
Here is the list of possible options −
 expand − When set to true, widget expands to fill any space not otherwise used in widget's parent.
 fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own
minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH
(fill both horizontally and vertically).
 side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT,
or RIGHT.
Example:
by moving cursor on different buttons −
from Tkinter import *

root = Tk()
frame = Frame(root)
frame.pack()

bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )

redbutton = Button(frame, text="Red", fg="red")


redbutton.pack( side = LEFT)

greenbutton = Button(frame, text="green", fg="green")


greenbutton.pack( side = LEFT )

bluebutton = Button(frame, text="Blue", fg="blue")


bluebutton.pack( side = LEFT )

blackbutton = Button(bottomframe, text="Black", fg="black")


blackbutton.pack( side = BOTTOM)

root.mainloop()
OUTPUT:

2.grid() method: It organizes the widgets in grid (table-like structure) before placing in the parent
widget. The master widget is split into a number of rows and columns, and each “cell” in the resulting
table can hold a widget.

Syntax :
widget.grid( grid_options )
Here is the list of possible options −
 column − The column to put widget in; default 0 (leftmost column).
 columnspan − How many columns widgetoccupies; default 1.
 ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's
borders.
 padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders.
 row − The row to put widget in; default the first row that is still empty.
 rowspan − How many rowswidget occupies; default 1.
 sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is centered in
its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and
SW, compass directions indicating the sides and corners of the cell to which widget sticks.
Consider the following example –

# import tkinter module


from tkinter import * from tkinter.ttk import *

# creating main tkinter window/toplevel


master = Tk()

# this will create a label widget


l1 = Label(master, text = "First:")
l2 = Label(master, text = "Second:")

# grid method to arrange labels in respective


# rows and columns as specified
l1.grid(row = 0, column = 0, sticky = W, pady = 2)
l2.grid(row = 1, column = 0, sticky = W, pady = 2)

# entry widgets, used to take entry from user


e1 = Entry(master)
e2 = Entry(master)

# this will arrange entry widgets


e1.grid(row = 0, column = 1, pady = 2)
e2.grid(row = 1, column = 1, pady = 2)

# infinite loop which can be terminated by keyboard


# or mouse interrupt
mainloop()

output:

3. place() method:It organizes the widgets by placing them on specific positions directed by the
programmer.
Syntax :

widget.place( place_options )
Here is the list of possible options −
 anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW,
compass directions indicating the corners and sides of widget; default is NW (the upper left corner
of widget)
 bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside
(ignoring the parent's border); OUTSIDE otherwise.
 height, width − Height and width in pixels.
 relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height
and width of the parent widget.
 relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height
and width of the parent widget.
 x, y − Horizontal and vertical offset in pixels.
Example :
Try the following example by moving cursor on different buttons −
from Tkinter import *
import tkMessageBox
import Tkinter

top = Tkinter.Tk()

def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")

B = Tkinter.Button(top, text ="Hello", command = helloCallBack)

B.pack()
B.place(bordermode=OUTSIDE, height=100, width=100)
top.mainloop()
When the above code is executed, it produces the following result −

# Importing tkinter module


from tkinter import *

# creating Tk window
master = Tk()

# setting geometry of tk window


master.geometry("200x200")

# button widget
b1 = Button(master, text = "Click me !")
b1.place(relx = 1, x =-2, y = 2, anchor = NE)

# label widget
l = Label(master, text = "I'm a Label")
l.place(anchor = NW)

# button widget
b2 = Button(master, text = "GFG")
b2.place(relx = 0.5, rely = 0.5, anchor = CENTER)

# infinite loop which is required to


# run tkinter program infinitely
# until an interrupt occurs
mainloop()
Output:

These are the widgets are used in our project :

1. Window creation:

from tkinter import *

window=Tk()

window.title("Hello")

window.mainloop()

OUTPUT:
2.Canvas widget

The Canvas widget lets us display various graphics on the application. It can be used to draw simple shapes
to complicated graphs. We can also display various kinds of custom widgets according to our needs.
from tkinter import *

window=Tk()

window.title("Hello")

Canvas1 = Canvas(window)

Canvas1.config(bg="#ff6e40")

Canvas1.pack(expand=True,fill=BOTH)

window.mainloop()

OUTPUT:

3.Label Widget

Tkinter Label is a widget that is used to implement display boxes where you can place text or images. The
text displayed by this widget can be changed by the developer at any time you want. It is also used to
perform tasks such as to underline the part of the text and span the text across multiple lines. It is important
to note that a label can use only one font at a time to display text. To use a label, you just have to specify
what to display in it (this can be text, a bitmap, or an image).
from tkinter import *

window=Tk()

window.title("Hello")

window.minsize(800,800)

headingLabel = Label(window, text="Welcome to \n Chettinad Vidyashram", bg='green', fg='white',


font=('Courier',15))

headingLabel.pack(side =LEFT,padx=50)

window.mainloop()

OUTPUT:
Program for username and password
from tkinter import *

from tkinter import messagebox

def submit():
u1=user.get()

p1=pw.get()

if u1=="uma" and p1=="cv2020":

messagebox.showinfo("success","correct username and password")

else:

messagebox.showinfo("error","invalid")

top = Tk()

top.geometry("450x300") # the label for user_name

user_name = Label(top,text = "Username").place(x = 40,y = 60) # the label for user_password

user_password = Label(top,text = "Password").place(x = 40, y = 100)

submit_button = Button(top,text = "Submit",command=submit).place(x = 40, y = 130)

user = Entry(top,width = 30)

user.place(x = 110, y = 60)

pw = Entry(top,show='*', width = 30)

pw.place(x = 110, y = 100)

top.mainloop()

OUTPUT:

Program for date validation


from datetime import *

while(True):

date=input("Enter date(yyyy/mm/dd):")
try:

datetime.strptime(date,'%Y/%m/%d')

print("This is correct",date,"format") # this msg is not neccessary, just to check

break

except:

print("This is incorrect",date,"format")

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy