Python Tutorial: Python GUI Programming (Tkinter)

(Python GUI Programming)
Python is a scripting language, In this post, you’ll learn how to build a GUI with python using the Tkinter GUI toolkit.

1) What is Python?

CtechF - Python

Python is a scripting language and that is used for creating engineering-analysis tools, web development (server-side), software development, system scripting, and animation software. It designed by Guido van Rossum and first released in 1991. It’s an interpreted, High-level. General-purpose language. Python runs on Windows, Mac OS, and Linux.

Python Tutorial: Introduction for Beginners (Part 1)
Python Tutorial: Introduction for Beginners (Part 2)
SQL Tutorial: Introduction for beginners (Basic)
Python Tutorial: How to Connect MySQL Database in Python

2) What is GUI?

GUI (Graphical User Interface) is an interface that used an icon, windows, menus, buttons or other visual indicators to interact with hardware. all version of Microsoft Windows is a GUI, MS-DOS is a command line. GUI was first developed at Xerox PARC by Alan Kay and Douglas Engelbart in 1981. GUI Operating Systems (OS ) is mainly navigated using a mouse.

python gui programming
CLI – Command Line Interface
python gui programming
GUI – Graphical User Interface

3) Python GUI Programming

Many applications need GUI. Python provides many toolkits for writing GUI based programs. such as Tkinter, wxPython, JPython, and PyQt. These toolkits will work with Windows, macOS, Linux, and etc…

Tkinter – Tkinter is the Python interface to the Tk GUI toolkit. It is a standard GUI library for Python and commonly used one.

Tcl/Tk Home Page

wxPython – wxPython is a cross-platform GUI toolkit for the Python. This means that the same program will run on multiple platforms without modification (Windows, MacOS X, macOS, and Linux). It is a Python wrapper around a C++ library called wxWidgets. It is an open-source an developed by Robin Dunn and Harri Pasanen.

wxPython Home Page

JPython – JPython (Jython) is an implementation of Python It designed to run on the Java platform. It is a Python port for Java which gives scripts seamless access to Java Class Libraries.

JPython Home Page

PyQt – PyQt is one of the most powerful GUI libraries. PyQt provides a binding for Qt4 and Qt 5. PyQt is developed by Riverbank Computing Limited. It is implemented as a set of Python modules. It is a multi-platform GUI toolkit. PyQt is available in two editions (Qt4 and Qt5) PyQt4 runs on Windows, MacOS Xm Linux, and UNIX platforms. also runs on Android and iOS.

PyQt Home Page

Python GUI Programming – tkinter

* Import tkinter

The name of Tkinter has changed from Tkinter (Python 2) to tkinter (Python 3).

# for Python2
from Tkinter import *

# for Python3
from tkinter import *

* Start

from tkinter import *
scr = Tk()
scr.title("Python and GUI - Start")
scr.geometry('300x200')

#Widgets

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Label

name = Label(Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Label - Tkinter Widgets")

lbl = Label(scr, text="Hello", padx=5, pady=10, fg="blue", bg="white", font=("Arial Bold", 20))

lbl.pack()
scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Label (get properties list)

You could get properties (option) list with dict() command. You can use this command for every widget.

dict(Widget name)
from tkinter import *
from pprint import pprint

scr = Tk()
scr.title("Label - Tkinter Widgets")

lbl = Label(scr, text="Hello", padx=5, pady=10, font=("Arial Bold", 20))

lbl.pack()
pprint(dict(lbl))
scr.mainloop()

Output:

python gui programming

* Tkinter Variable

BooleanVar – Boolean (True and False)
DoubleVar – Double (1.24, 5.1, 954.25)
IntVar – Integer (1, 900, 2541)
StringVar – String (“Hello”, “CtechF”, “New”)

variable_name = StringVar()
variable_name.set("value") #Set Variable

* Tkinter Widgets – Image

name = Label(Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Image - Tkinter Widgets")

imagelogo = PhotoImage(file='ctechf.png')
imagelbl = Label(scr, image=imagelogo)
imagelbl .pack()

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Button

name = Button(Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Button - Tkinter Widgetes")

def helloworld():
    print("Hello GUI")

btn = Button(scr, text ="Hello", fg="#FF0000", padx=10, pady=10, command = helloworld)
btn.pack()

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Tk Message Box

messagebox.function(title, message, [, options])

You can use the following functions,
* showinfo()
* showwarning()
* showerror ()
* askquestion()
* askokcancel()
* askyesno ()
* askretrycancel ()

from tkinter import *
from tkinter import messagebox
scr = Tk()
scr.title("Tk Message Box - Tkinter Widgets")
scr.geometry('300x200')

def msg():
   messagebox.showinfo("Title", "Message")

btn = Button(scr, text = "Click me", command = msg)
btn.pack()

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Message

name = Message(Windows name, option = value)
from tkinter import *
from tkinter import messagebox

domain = "https://ctechf.com"
scr = Tk()
scr.title("Message - Tkinter Widgets")

txt = StringVar()
lbl = Message(scr, textvariable=txt)

txt.set(domain)
lbl.pack()

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Check Buttons

name = Checkbutton(Windows name, option = value)
from tkinter import *

scr = Tk()
scr.title("Check Button - Tkinter Widgets")

value = BooleanVar() 
value.set(True)

chk1 = Checkbutton(scr, text = "HTML", height=2, width = 20, var=value)
chk2 = Checkbutton(scr, text = "PHP", height=2, width = 20)
chk3 = Checkbutton(scr, text = "CSS", height=2, width = 20, cursor="dotbox")
chk4 = Checkbutton(scr, text = "Ruby", height=2, width = 20)

chk4.select()

chk1.pack()
chk2.pack()
chk3.pack()
chk4.pack()

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Check Buttons (Get Data)

from tkinter import *

scr = Tk()
scr.title("Check Button (Get Data) - Tkinter Widjgets")
var1 = IntVar()

def display():
    value = var1.get()
    select = ""
    if(value == 1):
        select = "Thank you"
    else:        
        select = "Click I Guess"
   
    label.config(text = select, font=("Arial", 20))

chk1 = Checkbutton(scr, text = "I Guess", var=var1, onvalue=1, offvalue="0",  command=display)
label = Label(scr)

label.pack()
chk1.pack()

scr.mainloop()

Output:

python gui programming
python gui programming

* Tkinter Widgets – Radio Buttons

name = Radiobutton(Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Radio Button - Tkinter Wifgets")
var = IntVar()

rbtn1 = Radiobutton(scr, text="Male", variable=var, value=3)
rbtn2 = Radiobutton(scr, text="Female", variable=var, value=2)
rbtn3 = Radiobutton(scr, text="Others", variable=var, value=1)

rbtn1.grid(column=0, row=0)
rbtn2.grid(column=1, row=0)
rbtn3.grid(column=2, row=0)

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Radio Buttons (Get Data)

from tkinter import *
scr = Tk()
scr.title("Radio Button (Get Date) - Tikinter Widgets")
var = StringVar()

def display():
   selection = "Gender: " + str(var.get())
   label.config(text = selection)

rbtn1 = Radiobutton(scr, text="Male", variable=var, value="Male", command=display)
rbtn2 = Radiobutton(scr, text="Female", variable=var, value="Female", command=display)
rbtn3 = Radiobutton(scr, text="Others", variable=var, value="Others", command=display)
label = Label(scr)

rbtn1.pack(anchor = W)
rbtn2.pack(anchor = W)
rbtn3.pack(anchor = W)
label.pack()

scr.mainloop()

Output:

python gui programming
python gui programming

* Tkinter Widgets – Entry

name = Entry(Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Entry - Tkinter Widgets")
scr.geometry('300x100')

#Labels
labelname = Label(scr, text = "Name: ")
labelname.pack()

#Variables
namevar = StringVar()
namevar.set("No Name") #Defalt Value

#Entry
entryname = Entry(scr, width=20, textvariable=namevar)
entryname.pack()

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Entry (Complete)

from tkinter import *
scr = Tk()
scr.title("Entry (Complete) - Tkinter Widgets")

def result():
    resultString.set("{} : {}".format(namevar.get(), ctvar.get()))

#Labels
labelname = Label(scr, text = "Name: ")
labelname.grid(column=0, row=0)
labelct = Label(scr, text = "Country")
labelct.grid(column=0, row=1)

#Variables
namevar = StringVar()
ctvar = StringVar()

#Entry
entryname = Entry(scr, width=20, textvariable=namevar)
entryname.grid(column=1, row=0, padx=10)
entryct = Entry(scr, width=20, textvariable=ctvar)
entryct.grid(column=1, row=1, padx=10)

#Button
outbutton = Button(scr, text = 'Get Output', command=result)
outbutton.grid(column=2, row=2, pady=10)

#Output
resultString = StringVar()
resultLabel = Label(scr, textvariable=resultString)
resultLabel.grid(column=2, row=1, pady=10)

scr.mainloop()

Output:

python gui programming
python gui programming

* Tkinter Widgets – Combobox

name = Combobox(Windows name, values=["value 1","value 2","value 3"])

* Import

#For Python 2
from Tkinter import *
from ttk import *

#For Python 3
from tkinter import *
from tkinter.ttk import *
#For Python 3
from tkinter import *
from tkinter.ttk import *

scr = Tk()
scr.title("Combobox - Tkinter Widgets")
scr.geometry('300x100')

def select():
    value = "Value: " + combo.get()
    label.config(text = value)
    
combo = Combobox(scr, values=[ "Python", "PHP", "HTML", "MySQL", "C++", "OUT"])
combo.current(0)
combo.pack()

button = Button(scr, text="Select", command=select)
button.pack()

label = Label(scr)
label.pack()

scr.mainloop()

Output:

python gui programming
python gui programming

* Tkinter Widgets – Option Menu

name = OptionMenu("Windows name, variable, "value 1", "value 2", "value 3")
from tkinter import *
scr = Tk()
scr.title("Optioon Menu - Tkinter Widgets")
scr.geometry('300x100')

def select():
    print ("Value is: ", var.get())

var = StringVar(scr)
var.set("Google") #Default Value

option = OptionMenu(scr, var, "Google", "Bing", "DuckDuckGo", "Wiki")
option.pack()


button = Button(scr, text="Select", command=select)
button.pack()

mainloop()

Output:

python gui programming
python gui programming
python gui programming

* Tkinter Widgets – Option Menu (With GUI Output)

name = OptionMenu("Windows name, variable, "value 1", "value 2", "value 3")
from tkinter import *

scr = Tk()
scr.title("Option Menu - Tkinter Widget")
scr.geometry('300x100')

link = ""

def select():
    value = var.get()
    if (value == "Google"):
        link = "https://www.google.com"
    elif (value == "Bing"):
        link = "https://www.bing.com"
    elif (value == "DuckDuckGo"):
        link = "https://duckduckgo.com/"
    else:
        link = "https://www.yahoo.com/"
        
    label.config(text = link, fg="blue", cursor="hand2")

var = StringVar(scr)
var.set("Google") #Default Value

option = OptionMenu(scr, var, "Google", "Bing", "DuckDuckGo", "Yahoo")
option.pack()

button = Button(scr, text="Select", command=select)
button.pack()

label = Label(scr)
label.pack()

mainloop()

Output:

python gui programming

* Tkinter Widgets – List Box

name = Listbox("Windows name, option = value)
from tkinter import *

scr = Tk()
scr.title("List Box - Tkinter Widgets")
scr.geometry('300x200')

listb = Listbox(scr) 
listb.insert(1, 'Python') 
listb.insert(2, 'PHP') 
listb.insert(3, 'Java') 
listb.insert(4, 'MySQL')
listb.insert(5, 'NodeJS')
listb.pack() 

mainloop()

Output:

python gui programming

* Tkinter Widgets – Scale

name = Scale("Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Scale - Tkinter Widgets")
scr.geometry('200x100')

var = DoubleVar()
scale = Scale(scr, variable = var, orient=HORIZONTAL, resolution=0.1)
scale.pack()

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Scale – More

from tkinter import *
scr = Tk()
scr.title("Scale (More) - Tkinter Widgets")

def val():
   select = "Value = " + str(var.get())
   label.config(text = select)
   
   select1 = "Value = " + str(var1.get())
   label1.config(text = select1)

#HORIZONTAL Scale
var = DoubleVar()
scale = Scale(scr, variable = var, orient=HORIZONTAL, resolution=0.1)
scale.pack(anchor=CENTER)
label = Label(scr)
label.pack()

#VERTICAL Scale
var1 = DoubleVar()
scale = Scale(scr, variable = var1, orient=VERTICAL, from_=10, to=50,)
scale.pack(anchor=CENTER)
label1 = Label(scr)
label1.pack()

button = Button(scr, text="Get Scale Values", command=val)
button.pack(anchor=CENTER)

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – SpinBox

name = SpinBox("Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Spin Box - Tkinter Widgets")
scr.geometry('200x100')

sbox = Spinbox(scr, from_ = 0, to = 10) 
sbox.pack() 

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – TopLevel

name = TopLevel("Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Main Window")
scr.geometry('300x100')

scr1 = Toplevel(scr, bg = "red") 
scr1.title('Top Level Window') 
scr1.geometry('300x200')

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Menubar

name = Menu("Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Menu Bar")
scr.geometry('300x100')

menubar = Menu(scr)

fmenu = Menu(menubar)
fmenu.add_command(label="Open")
fmenu.add_command(label="Save as")
fmenu.add_command(label="Save")
fmenu.add_command(label="Quit")

menubar.add_cascade(label="File", menu=fmenu)

scr.config(menu=menubar)
scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Menubar with Dialogs (Open)

from tkinter import *
from tkinter import filedialog
scr = Tk()
scr.title("Open File - Tkinter Widgets")
scr.geometry('300x200')

def dopen():
    print(filedialog.askopenfilename(initialdir = "/",title = "Open file",filetypes = (("Text files","*.txt"),("All files","*.*"))))
 
menubar = Menu(scr)

filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=dopen)
filemenu.add_command(label="Exit", command=scr.quit)

menubar.add_cascade(label="File", menu=filemenu)
scr.config(menu=menubar)

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Menubar with Dialogs (Save as)

from tkinter import *
from tkinter import filedialog
scr = Tk()
scr.title("Save as")
scr.geometry('300x200')

def dsave():
    print(filedialog.asksaveasfilename(initialdir = "/",title = "Save as",filetypes = (("Text files","*.txt;*.no"),("All files","*.*"))))

menubar = Menu(scr)

filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Save as", command=dsave)
filemenu.add_command(label="Exit", command=scr.quit)

menubar.add_cascade(label="File", menu=filemenu)
scr.config(menu=menubar)

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Scroll Bar

from tkinter import *
scr = Tk()
scr.title("Scroll Bar - Tkinter Widgets")

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

newlist = Listbox(scr, yscrollcommand = sb.set)

for line in range(50): 
   newlist.insert(END, "Scroll Bar: Line " + str(line)) 
newlist.pack(side = LEFT, fill = BOTH )

sb.config(command = newlist.yview)

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Status Bar

from tkinter import *
scr = Tk()
scr.title("Status Bar")
scr.geometry('200x100')

statusbar = Label(scr, text="https://ctechf.com", bd=2, relief=SUNKEN, anchor=W)

statusbar.pack(side=BOTTOM, fill=X)
scr.mainloop()

Output:

python gui programming

* Tkinter Widgets –  Label Frame

name = LabelFrame("Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Label Frame - Tkiniter Widgets")
scr.geometry('200x100')

lf = LabelFrame(scr, text="Label Frame")
lf.pack(fill="both", expand="yes")
 
btn = Button(lf, text ="Hello", fg="red", padx=10, pady=10)
btn.pack()

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Frame

name = LabelFrame("Windows name, option = value)
from tkinter import *
scr = Tk()
scr.title("Frame = Tkinter Widgets")
scr.geometry('400x50')

#Frame 1
frame = Frame(scr)
frame.pack(side = LEFT)

redbutton = Button(frame, text="Button 0", bg="red", fg="white")
redbutton.pack(side = LEFT)
greenbutton = Button(frame, text="Button 1", bg="green", fg="white")
greenbutton.pack(side = LEFT)
bluebutton = Button(frame, text="Button 1", bg="blue", fg="white")
bluebutton.pack(side = LEFT)


#Frame 2
frame1 = Frame(scr)
frame1.pack(side = RIGHT)

blackbutton = Button(frame1, text="Button 0", fg="black")
blackbutton.pack(side = RIGHT)
blackbutton = Button(frame1, text="Button 1", fg="black")
blackbutton.pack(side = RIGHT)

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets – Events and Bindings (Mouse)

widget_name.bind(event, handler)
from tkinter import *
scr = Tk()
scr.title("Mouse Event - Tkinter Widgets")
scr.geometry('400x500')

def mouse(event):
    print ("Clicked XY", event.x, event.y)
  
frame = Frame(scr, width=400, height=500)
frame.bind("<Button-1>", mouse)
frame.pack()

scr.mainloop()

Output:

python gui programming

* Tkinter Widgets -Events and Bindings (Keyboard)

from tkinter import *
scr = Tk()
scr.title("Keybord Event - Tkinter Widgets")
scr.geometry('200x100')

def keyboard(event):
    print ("Pressed Key: ", repr(event.char))
    
frame = Frame(scr, width=200, height=100)
frame.focus_set()
frame.bind("<Key>", keyboard)
frame.pack()

scr.mainloop()

Output:

python gui programming

Download above Python .py file: Drive link

For more information, Visit: https://effbot.org/tkinterbook/

Sources: 
https://pixabay.com (Images)

Hi Guys,

Hope this post (Python Tutorial: Python GUI Programming (Tkinter)) will help you to learn something. If you enjoy my work, please Share my posts with your friends and anyone who might be interested in programming. Don’t forget to Comment and, Subscribe.

What do you think about Python
See you in the comment section.

Like ctechf Facebook fan page : https://www.facebook.com/ctechf

Also Read :

How to be a Programmer

Liked it? Take a second to support CtechF on Patreon!

Leave a Reply

454 Shares
Share
Tweet
Share
Pin
Share