Professional Documents
Culture Documents
Session 4 Worksheet - Tkinter - 1
Session 4 Worksheet - Tkinter - 1
(Session – 4)
There are basically five main steps that are required to get your GUI up
and running:
1. Import the Tkinter module (or from Tkinter import *).
2. Create a top-level windowing object that contains your entire GUI
application.
3. Build all your GUI components (and functionality) on top (or
within) of your top-level windowing object.
4. Connect these GUI components to the underlying application
code.
5. Enter the main event loop.
Callbacks -
from Tkinter import *
root = Tk()
def quit():
print 'Hello, getting out of here’
import sys; sys.exit()
Binds –
import tkinter as tk
root = Tk()
def hello(event):
print('Double click to exit')
def quit(event):
print ('caught a double click, leaving')
import sys
sys.exit()
MessageBox
• showinfo()
The showinfo() messagebox is used where we need to show some
relevant information to the user.
• showwarning()
This method is used to display the warning to the user.
• showerror()
This method is used to display the error message to the user.
Consider the following example.
• askquestion()
This method is used to ask some question to the user which can
be answered in yes or no.
• askokcancel()
This method is used to confirm the user's action regarding some
application activity.
• askyesno()
This method is used to ask the user about some action to which,
the user can answer in yes or no.
• askretrycancel()
This method is used to ask the user about doing a particular task
again or not.
root = Tk()
messagebox.showinfo("information","Information")
root.pack()
root.mainloop()
ASSIGNMENTS
ASSIGNMENT 1 –
Justifying Text on Label and Adding Padding around Text
mytext = """
There are different parts of the computer.
They are : CPU, Monitor, Keyboard and Mouse.
"""
More on Buttons
from tkinter import *
from tkinter import messagebox
def displayred():
messagebox.showinfo("Hello", "Red Button clicked")
root = Tk()
root.title("Colourful Buttons")
rbutton = Button(root, text='RED', activeforeground =
"red",activebackground = "pink", width=25, command=displayred)
rbutton.pack(side = "left")
root.mainloop()