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

PythonGUI

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

PythonGUI

python
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Python - GUI Programming (Tkinter)

Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.

Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We
would look this option in this chapter.

Tkinter Programming: Tkinter is the standard GUI library for Python. Python when
combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter
provides a powerful object-oriented interface to the Tk GUI toolkit.

Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −

1. Import the Tkinter module.

2. Create the GUI application main window.

3. Add one or more widgets to the GUI application.

4. Enter the main event loop to take action against each event triggered by the user.

1. Importing tkinter is same as importing any other module in the Python code.

import Tkinter as tk

There are two main methods used which the user needs to remember while creating the
Python application with GUI.

2.Tk(): To create a main window,The basic code used to create the main window of the
application is:

m=tk.Tk() , where m is the name of the main/parent window object.

4. mainloop(): The method 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()

Example1:

import tkinter

m = tkinter.Tk()

'''widgets are added here'''

m.mainloop()
Example2:

Creating a blank window:

import tkinter as tk

my_w = tk.Tk()

my_w.geometry("500x500") # Size of the window

my_w.title("www.plus2net.com") # Adding a title

my_w.mainloop() # Keep the window open

my_w.destroy() # Close the window

my_w.bind('<Escape>', lambda e:my_w.quit()) #close by using Esc key

Options for main window:

geometry():

my_w.geometry("400x350+410+100") # Size & Position

400 : width of the window, 350 : Height of the window

410 : Position (opening ) of the window from left or X position,

100 : Position (opening ) of the window from Top or Y position

Resizing of window is possible by default, but we can manage this setting by making resizing height,
width to False

my_w.resizable(width=0,height=0) # resizing of window is not allowed

Or

my_w.resizable(False,False)

While opening the window we can set to full screen.

Values for this option are normal (default value ) , iconic, withdrawn, or zoomed.

my_w.state('zoomed')

We can change the background colour

my_w.configure(background='black')

OR

my_w.configure(background='#FFFF00')
Python Tkinter Geometry:

The Tkinter geometry specifies the method by using which, the widgets are represented or
placed on main window. The python Tkinter provides the following geometry methods.

1. pack() : It organizes the widgets in blocks before placing in the parent widget. Places the
widget following the previous.

Syntax: 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: Mybutton.pack(side = BOTTOM)

2. grid() :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
columnspan (width) or rowspan(height) of a widget.

Syntax: 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. Leftmost column is 0.

row: row number in which the widget is to be placed. The topmost row is represented by 0.

columnspan: width of the widget, number of columns up to which, the column is expanded.

rowspan: height of the widget, i.e. the number of the row up to which the widget 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.

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.

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

Place a widget in a location relative to the upper left corner of parent.

The values are between 0.0 and 1.0.


widget.place(relx=n.n, rely=n.n, options)

Location can also be specified as an absolute x,y position.

widget.place(x=n, y=n, options)

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: email = Label(top, text = "Email").place(x = 30, y = 90)

Tkinter widgets:

There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build
the python GUI applications. Following is the list of main widgets in Tkinter.

1.Button:The Button is used to add various kinds of buttons to the python application.

2.Canvas:The canvas widget is used to draw the canvas on the window.The Canvas is a
rectangular area intended for drawing pictures or other complex layouts. You can place
graphics, text, widgets or frames on a Canvas.

3.Checkbutton: The Checkbutton is used to display the CheckButton on the window.


Checkbutton is used to provide many choices to the user.

4.Entry: The entry widget is used to display the single-line text field to the user. It is
commonly used to accept user values.

5.Frame: It can be defined as a container to which, another widget can be added and
organized.

6. Label: A label is a text used to display some message or information about the other
widgets.

7.ListBox:TheListBox widget is used to display a list of options to the user. The user can
choose more than one item from the list to be displayed

8.Menubutton:TheMenubutton is used to display the menu items to the user.

9.Menu:It is used to add menu items to the user.

10.Message:The Message widget is used to display the message-box to the user.

11.Radiobutton:TheRadiobutton is different from a checkbutton. Here, the user is provided


with various options and the user can select only one option among them.

12.Scale: It is used to provide the slider to the user.


13.Scrollbar:It provides the scrollbar to the user so that the user can scroll the window up and
down. Scrollbar helps user to scroll and view the entire content.

14.Text: It is different from Entry because it provides a multi-line text field to the user so that
the user can write the text and edit the text inside it.

15.Spinbox:It is an entry widget used to select from options of values. Using Spinbox user
can select value from a range of given options.

16.LabelFrame: LabelFrame widget is a container that contains other related widgets. For
example, you can group Radiobutton widgets and place the group on a LabelFrame.

17.MessageBox:This module is used to display the message-box in the desktop based


applications.

1.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.

The syntax to use the button widget is given below.

Syntax: B = Button(parent, options)

Example:

import tkinter as tk

my_w = tk.Tk()

my_w.geometry("500x500")

my_font=('times', 8, 'bold')

b1 = tk.Button(my_w, text='Hi Welcome',

width=20,bg='yellow',font=my_font,fg='green')

b1.pack()

my_w.mainloop()

Now let us add the click event of the button. This will close the window.
b1 = tk.Button(my_w, text='Hi Welcome', width=20,bg='yellow',

command=my_w.destroy())

To execute a function on click of button ( here function name is my_upd() )

b1 = tk.Button(my_w, text='Hi Welcome', width=20,bg='yellow',

command=lambda: my_upd())

There are many optional options we can add to button

1.bg/background: Background color of the button.

b1=tk.Button(my_w,text='My Button',width=10,bg='green')

2. bd :borderwidth

b1=tk.Button(my_w,text='My Button',width=10,bg='yellow',bd=5)

3. activebackground: Background Colour of the button when button is active or pressed.

b1=tk.Button(my_w,text='MyButton',width=10,activebackground='red')

4. activeforeground:Foregroundcolor (font ) of the button when button is active or pressed.

b1=tk.Button(my_w,text='B1',width=10,activeforeground='green')

5. command :A callback function to execute when the button is pressed.

import tkinter as tk

my_w=tk.Tk()

my_w.geometry('200x100')

def my_upd():

print('hi')

b1 = tk.Button(my_w, text='Yellow',command=lambda: my_upd())

b1.grid(row=1,column=1)

my_w.mainloop()

6. cursor:Shape of the cursor when it is placed over the button.

b1=tk.Button(my_w,text='My Button',width=10,cursor='boat')

7. font:Font size style of the button.(Font type and Font style)

b1=tk.Button(my_w,text='My Button',width=10,font=18)
# We can use variable for type and style.

my_font=('times', 8, 'underline')

b1=tk.Button(my_w,text='My Button',width=10, font=my_font)

8. fg: foreground

b1=tk.Button(my_w,text='My Button',width=10, fg='red')

9. height:Height of the buttons ( We can manage size of the button using height and width )

b1=tk.Button(my_w,text='My Button',width=10,height=3)

10. highlightbackground:Bordercolor when the button is not in focus.

b1=tk.Button(my_w,text='B1',highlightbackground='red',bd=5)

11.highlightcolor:Border colour when the button is in focus.

b1=tk.Button(my_w,text='B1',width=10,highlightcolor='red',bd=5)

12.padx :Horizontal padding between text and border.

13.pady :Vertical padding between text and border

b1=tk.Button(my_w,text='B1',width=5,height=1, padx=20,pady=10)

14. relief:The Button (borders) 3D effect style.Take values raised , sunken ,flat, ridge, solid
& groove.

t1 = tk.Button(my_w,height=10,relief='raised')

15. overrelief:Similar to relief but all effects takes place when Mouse is over the button.

t1 = tk.Button(my_w, width=10,height=1,overrelief='groove')

16.text:The text written over the button

b1=tk.Button(my_w, text='First ',width=12,height=1)

17.underline: Underline the button text character given by the position.

b1=tk.Button(my_w,text='MyButton',width=15,height=1,underline=3)

18.width:width of the button in Chars

b1=tk.Button(my_w,text='My Button', width=15,height=1)

19. image:Image we can display on the button.


b1=tk.Button(my_w,image=my_img, relief='flat')

Button Methods:There are two methods, flash() and invoke().

The invoke() method used to Trigger events without Clicking the button

We can simulate the button click event by using invoke().

Example:

import tkinter as tk # Python 3

my_w = tk.Tk()

my_w.geometry("420x200") # width and height of the window

b1=tk.Button(my_w,text='One',font=28,

command=lambda :l1.config(text='Button One '))

b1.grid(row=0,column=0,padx=30,pady=10)

b2=tk.Button(my_w,text='Two',font=28,

command=lambda :l1.config(text='Button Two'))

b2.grid(row=0,column=1,padx=10,pady=10)

#command=lambda :l1.config(text='Button Two')

#command=lambda :b1.invoke()

l1=tk.Label(my_w,text='No Click ',bg='yellow',

width=13,font=('Times',26,'normal'))

l1.grid(row=1,column=0,padx=30,pady=10,columnspan=3)

#b2.invoke() # Click or Command of button 2

my_w.mainloop()

Here the default text on the Label l1 will be displayed and the same will change on click of
any button.

By adding the line b2.invoke() we can show the text of button b2 on Label l1 . This is the
default behavior which without the click of Second button b2.

We can change the command part of button b2 to call the button 1 click event.

import tkinter as tk

my_w = tk.Tk()
my_w.geometry("420x200")

b1=tk.Button(my_w,text='One',font=28,

command=lambda :l1.config(text='Button One '))

b1.grid(row=0,column=0,padx=10,pady=10)

b2=tk.Button(my_w,text='Two',font=28,

command=lambda :b1.invoke())

b2.grid(row=0,column=1,padx=10,pady=10)

#command=lambda :l1.config(text='Button Two')

#command=lambda :b1.invoke()

l1=tk.Label(my_w,text='No Click',bg='yellow',font=('Times',26,'normal'))

l1.grid(row=1,column=0,padx=2,pady=10,columnspan=3)

b2.invoke() # Click or Command of button 2

my_w.mainloop()

flash() : Drawing user attention. We can flash() the button by changing the colour from active
to normal several times.

B1.flash() # flashing the button

Example : Here we are having two buttons, user must click the second button saying Click
Me to Agree before clicking the Submit button.

If the user clicks the Submit button without Clicking the Agree button, then this button will
flash several times drawing the user attention to click it.

import tkinter as tk

my_w = tk.Tk()

my_w.geometry("400x200") # width and height of the window

font1=('Times',22,'normal') # declaring font Family, size and style

def my_upd():

if b2['text']=='Click Me to Agree': # check the text of 2nd button

b2.flash() # flashing the button

else:
b2['text']='Click Me to Agree' # change the text on the button

b1=tk.Button(my_w,text='Submit',font=font1,bd=6,command=my_upd)

b1.grid(row=0,column=1,padx=10,pady=60)

b2=tk.Button(my_w,text='Click Me to Agree',font=font1,bd=6,width=14,

command=lambda:b2.config(text='I agree'),

activebackground='red',activeforeground='yellow')

b2.grid(row=0,column=2,padx=5,pady=60)

my_w.mainloop()

2. Entry

The Entry widget is used to provide 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: E1=tk.Entry(parent_window,options)

A list of possible options is:

bg,bd,cursor,exportselection,fg,font,highlightbackground,highlightcolor,highlightthickness,in
sertbackground,insertborderwidth,insertofftime,insertontime,insertwidth,justify,relief,selectba
ckground,selectborderwidth,selectforeground,show,textvariable,width,xscrollcommand.

import tkinter as tk

my_w = tk.Tk()

my_w.geometry("250x150")

my_w.title("SCS-SRTMUN") # Adding a title

l1 = tk.Label(my_w, text='Your Name', width=10 ) # added one Label

l1.grid(row=1,column=1)

e1 = tk.Entry(my_w, width=20,bg='yellow') # added one Entry box

e1.grid(row=1,column=2)

my_w.mainloop()
#This code we will add one label.

import tkinter as tk

my_w=tk.Tk()

my_w.geometry('300x100')

my_w.title('Computer Application')

l3 = tk.Label(my_w, text='Welcome', width=15 )

l3.grid(row=1,column=1)

my_w.mainloop()

3. Checkbutton(Checkbox)

The Checkbutton is used to track the user's choices provided to the application. Checkbutton
is used to implement the on/off selections.

The Checkbutton can contain the text or images. Checkbutton is used to provide many
choices to the user.

Example: Checkbox:How many languages you know ? Answer can be more than one of the
given options like PHP, Python, JavaScript, JQuery. Here Checkbox or checkbuttons
representing one language as option is to be used.

Syntax: w = Checkbutton(master, options)

A list of possible options are:

activebackground,activeforeground,bg,bitmap,bd,command,cursor,disableforeground,font,fg
heighthighlightcolor,image,justify,offvalue,onvalue,padx,pady,relief,selectcolor,selectimage,s
tate,underline,variable,widthwraplength.

Example1:

import tkinter as tk

my_w = tk.Tk()

my_w.geometry("500x500") # Size of the window

c_v1=tk.IntVar()

c1 = tk.Checkbutton(my_w,text='PHP',variable=c_v1,onvalue=1,offvalue=0)

c1.grid(row=7,column=5)
my_w.mainloop() # Keep the window open

In above code we have linked the IntVar() variable c_v1 to the checkbutton. This value we
will be using for our reading and writting (setting) the status of the checkbutton.

onvalue=1 mean the variable c_v1 will get value 1 when checkbutton is clicked. or checked

offvalue=0 mean the variable c_v1 will get value 0 when checkbutton is unchecked

How to read the status (get value of the associated variable ) of the check box. ?

my_val=c1_v1.get() #c1_v1 is the variable connected to checkbutton

How to set the value of the checkbutton (to Check or Uncheck )?

c1_v1.set(1)

c1_v1.set(False)

Note that checkbutton can have values 1 or 0 ( integer variable ), Yes or No ( string variable)
, True or False ( Boolean variable )

c1_v1=tk.StringVar()

c1_v1=tk.BooleanVar()

Enable or Disable Checkbutton

By using config we can manage the state option of the Checkbutton.

c1.config(state='disabled') # c1 is the Checkbutton

c1.config(state='normal')

Example2:

import tkinter as tk

top = tk.Tk()

top.geometry("200x200")

checkvar1 = tk.IntVar()

checkvar2 = tk.IntVar()

checkvar3 =tk.IntVar()

chkbtn1 =tk.Checkbutton(top, text = "C", variable = checkvar1, onvalue = 1, offvalue = 0,


height = 2, width = 10)
chkbtn2 = tk.Checkbutton(top, text = "C++", variable = checkvar2, onvalue = 1, offvalue = 0,
height = 2, width = 10)

chkbtn3 = tk.Checkbutton(top, text = "Java", variable = checkvar3, onvalue = 1, offvalue = 0,


height = 2, width = 10)

chkbtn1.pack()

chkbtn2.pack()

chkbtn3.pack()

top.mainloop()

Methods:

The methods that can be called with the Checkbuttons are:

deselect():It is called to turn off the checkbutton.

flash():The checkbutton is flashed between the active and normal colors.

invoke():This will invoke the method associated with the checkbutton.

select(): It is called to turn on the checkbutton.

toggle() :It is used to toggle between the different Checkbuttons.

4.Radiobutton

This widget implements a multiple-choice button, which is a way to offer many possible
selections to the user and lets user choose only one of them.

In order to implement this functionality, each group of radiobuttons must be associated to the
same variable and each one of the buttons must symbolize a single value.

Syntax: Rbutton = Radiobutton(master, text= “Name on Button”, variable = “shared


variable”, value = “values of each button”, options = values, …)

shared variable = A Tkinter variable shared among all Radio buttons

value = each radiobutton should have different value otherwise more than 1 radiobutton will
get selected.

Options:activebackground,activeforeground,anchor,bg,bitmap,borderwidth,command,cursor,f
ont,fg,height,highlightcolor,highlightbackground,image,justify,padx,pady,relief,selectcolor,se
lectimage, state,text, textvariable,underline,value,variable,width,wraplength
import tkinter as tk

root = tk.Tk()

v = tk.IntVar()

tk.Label(root, text="""Choose a programming language:""",justify = tk.LEFT, padx =


20).pack()

tk.Radiobutton(root, text="Python",padx = 20, variable=v, value=1).pack(anchor=tk.W)

tk.Radiobutton(root, text="Perl",padx = 20, variable=v, value=2).pack(anchor=tk.W)

root.mainloop()

anchor:If the widget inhabits a space larger than it needs, this option specifies where the
radiobutton will sit in that space. The default is anchor=CENTER.

Methods:

deselect():Clears (turns off) the radiobutton.

flash():Flashes the radiobutton a few times between its active and normal colors, but leaves it
the way it started.

invoke():You can call this method to get the same actions that would occur if the user clicked
on the radiobutton to change its state.

select():Sets (turns on) the radiobutton.

5. Label

This widget is used to place text or images, which helps the user to know for what the other
widget is for. This widget provides a message as to what the widget will do to the user.

Syntax: Label (master, option = value)


Options are again the same as for the Entry widget, and there are many different options also.
Example:
from tkinter import *
root = Tk()
root.geometry("300x350")
r = Label(root, text='Python Training',width =35)
r.pack()
root.mainloop()
6. Listbox

Tkinter Listbox widget is used to display a list of items of which all are text items having the
same font and color. The user can choose more than one item from the list to be displayed
depending on the widget’s configuration.

syntax: w = Listbox(master, option)

The master represents the parent window, and the option is the list of options that can be used
for the widget, and options are the key-value pairs separated by commas.

import tkinter as tk

my_w = tk.Tk()

my_w.geometry("400x300") # Size of the window

my_w.title("Creating Listbox")

l1 = tk.Listbox(my_w,height=3)

l1.grid(row=1,column=1)

l1.insert(1,'PHP') # Adding element to Listbox

l1.insert(2,'Python')

l1.insert(3,'MySQL')

my_w.mainloop() # Keep the window open

state:It can be normal, active or disabled

selectmode: It can be SINGLE, BROWSE, MULTIPLE, EXTENDED

7. Scrollbar

Scrollbar helps user to scroll and view the entire content.

Tkinter Scrollbar widget basically provides the slide controller, which is used to implement
the vertical scrolling widgets like the Listbox, Canvas, and the Text.

Using the Tkinter scrollbar widget, one can also try creating the horizontal scrollbar on the
entry widgets.

Tkinter scrollbar is used to roll through the content to see the whole content vertically when
the scrollbar is set to vertical.
A horizontal scrollbar is used to scroll over the content horizontally. Scrollbar() syntax will
be used to get a scrollbar with the attributes: master and the option/options.

Syntax: w= scrollbar( master, option)

master: This master attribute of the Tkinter scrollbar represents only the parent window

options: The option attribute of the Tkinter scrollbar will have the list of option which are
commonly used for the scrollbar widget. These option mainly are used as the key-value pairs,
which are separated by the commas.

import tkinter as tk

from tkinter import *

my_w=tk.Tk()

my_w.geometry("350x200")

sb = tk.Scrollbar(my_w,cursor='hand1')

sb.pack(side=RIGHT,fill=Y)

l1 = tk.Listbox(my_w,height=8,width=90,bg='yellow', yscrollcommand = sb.set )

l1.pack(side=LEFT,padx=15)

for i in range(1, 40): # multiple lines added to Listbox

l1.insert(END, "Line No : " + str(i))

sb.config( command = l1.yview )

my_w.mainloop()

Options:

In above code we used cursor='hand' to change the cursor shape when it is over the scrollbar

orient:By default the option orient is 'vertical' , we can set it to horizontal to display the
Scrollbar in horizontal direction.

sb = tk.Scrollbar(my_w,orient='horizontal')
8.Spinbox:

Using Spinbox user can select value from a range of given options.

Two SpinBox widgets, one for integer and other one for string selection by user.

import tkinter as tk

my_w = tk.Tk()

my_w.geometry("300x150") # Size of the window

my_w.title("www.plus2net.com") # Adding a title

sb1 = Spinbox(my_w, from_= 0, to = 10,width=5)

sb1.grid(row=1,column=1,padx=20,pady=20)

my_list=['One', 'Two', 'Three', 'Four', 'Five']

sb2 = Spinbox(my_w,values=my_list,width=10)

sb2.grid(row=1,column=2,padx=20,pady=20)

my_w.mainloop() # Keep the window open

9. LabelFrame

LabelFrame widget is a container that contains other related widgets. For example, you can
group Radiobutton widgets and place the group on a LabelFrame.

w = LabelFrame( master, option )

master − This represents the parent window.

options − Here is the list of most commonly used options for this widget. These options can
be used as key-value pairs separated by commas.

from tkinter import *

root = Tk()

labelframe = LabelFrame(root, text="This is a LabelFrame")

labelframe.pack(fill="both", expand="yes")

left = Label(labelframe, text="Inside the LabelFrame")

left.pack()

root.mainloop()
To create a LabelFrame widget, you can also use ttk.LabelFrame:

from tkinter import Tk, mainloop

from tkinter.ttk import *

root1 = Tk()

root1.geometry('250x150')

labelframe = LabelFrame(root1, text = 'Welcome to Programming') # LabelFrame is created

labelframe.pack(expand = 'yes', fill = 'both')

button = Button(labelframe, text = 'option 1') # Buttons are defined and created

button.place(x = 30, y = 10)

button1 = Button(labelframe, text = 'option 2')

button1.place(x = 130, y = 10)

checkbutton1 = Checkbutton(labelframe, text = 'Checkbox 1') # Checkbuttons created

checkbutton1.place(x = 30, y = 50)

checkbutton2 = Checkbutton(labelframe, text = 'Checkbox 2')

checkbutton2.place(x = 30, y = 80)

mainloop()

You might also like