Font Selection Dialog Box Using Python And Tkinter

Well Friends, 






In Graphical Programming, 
                                       Font Selection Dialog Box are very important part to make GUI Setting More Easy To Understand for their user. basically, font selection dialog boxes help its user to select any specific font size, family Or type from a range of fonts.

So, Today, I am going to write about how we can create an simple font chooser/selection window for an text editor in python. Basically, Guys For this purpose here I am going to use tkFont module. 


What is tkFont Module?

Ans. Basically, tkFont is a Standard module comes with Tkinter Module. it's mean You Don't Need to Install it Separately But I'm not sure about your situation.

This module is very compatible for this purpose because its standard choice guys. and another advantages are like, using this module we can change font configurations simply. no need to Depend on other module. So, before starting let me show you a Screenshots of Font selecting dialog box created by me.





Looks Good.

So, Let'S Quickly Understand How I Wrote These Codes. But First, Copy All The Codes Given Below And Save It In A Text File As Fontbox.py

Do it! Then Read Further! Ok

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
try:
    import Tkinter
except:
    import tkinter as Tkinter
import tkFont,ttk


class Font_wm(Tkinter.Toplevel):
    def __init__(self, Font=None):

        Tkinter.Toplevel.__init__(self)
        self.mainfont=Font
        self.title('Font ...')

        # Variable
        self.var=Tkinter.StringVar()# For Font Face
        self.var.set(self.mainfont.actual('family'))
        self.var1=Tkinter.IntVar()  # for Font Size
        self.var1.set(self.mainfont.actual('size'))
        self.var2=Tkinter.StringVar() # For Bold
        self.var2.set(self.mainfont.actual('weight'))
        self.var3=Tkinter.StringVar() # For Italic
        self.var3.set(self.mainfont.actual('slant'))
        self.var4=Tkinter.IntVar()# For Underline
        self.var4.set(self.mainfont.actual('underline'))
        self.var5=Tkinter.IntVar() # For Overstrike
        self.var5.set(self.mainfont.actual('overstrike'))


        # Font Sample
        self.font_1=tkFont.Font()
        for i in ['family', 'weight', 'slant', 'overstrike', 'underline', 'size']:
            self.font_1[i]=self.mainfont.actual(i)

        # Function
        def checkface(event):
            try:
                self.var.set(str(self.listbox.get(self.listbox.curselection())))
                self.font_1.config(family=self.var.get(), size=self.var1.get(), weight=self.var2.get(), slant=self.var3.get(), underline=self.var4.get(), overstrike=self.var5.get())
            except:
               pass
        def checksize(event):
            try:
                self.var1.set(int(self.size.get(self.size.curselection())))
                self.font_1.config(family=self.var.get(), size=self.var1.get(), weight=self.var2.get(), slant=self.var3.get(), underline=self.var4.get(), overstrike=self.var5.get())
            except:
                pass            
        def applied():
            self.result=(self.var.get(), self.var1.get(), self.var2.get(), self.var3.get(), self.var4.get(), self.var5.get())
            self.mainfont['family']=self.var.get()
            self.mainfont['size']=self.var1.get()
            self.mainfont['weight']=self.var2.get()
            self.mainfont['slant']=self.var3.get()
            self.mainfont['underline']=self.var4.get()
            self.mainfont['overstrike']=self.var5.get()
        def out():
            self.result=(self.var.get(), self.var1.get(), self.var2.get(), self.var3.get(), self.var4.get(), self.var5.get())
            self.mainfont['family']=self.var.get()
            self.mainfont['size']=self.var1.get()
            self.mainfont['weight']=self.var2.get()
            self.mainfont['slant']=self.var3.get()
            self.mainfont['underline']=self.var4.get()
            self.mainfont['overstrike']=self.var5.get()
            self.destroy()
        def end():
            self.result=None
            self.destroy()
            
        # Main window Frame
        self.mainwindow=ttk.Frame(self)
        self.mainwindow.pack(padx=10, pady=10)
        # Main LabelFrame
        self.mainframe=ttk.Frame(self.mainwindow)
        self.mainframe.pack(side='top',ipady=30, ipadx=30,expand='no', fill='both')
        self.mainframe0=ttk.Frame(self.mainwindow)
        self.mainframe0.pack(side='top', expand='yes', fill='x', padx=10, pady=10)
        self.mainframe1=ttk.Frame(self.mainwindow)
        self.mainframe1.pack(side='top',expand='no', fill='both')
        self.mainframe2=ttk.Frame(self.mainwindow)
        self.mainframe2.pack(side='top',expand='yes', fill='x', padx=10, pady=10)
        # Frame in [  main frame]
        self.frame=ttk.LabelFrame(self.mainframe, text='Select Font Face')
        self.frame.pack(side='left', padx=10, pady=10, ipadx=20, ipady=20, expand='yes', fill='both')
        self.frame1=ttk.LabelFrame(self.mainframe, text='Select Font size')
        self.frame1.pack(side='left', padx=10, pady=10, ipadx=20, ipady=20, expand='yes', fill='both')
        ttk.Entry(self.frame, textvariable=self.var).pack(side='top', padx=5, pady=5, expand='yes', fill='x')
        self.listbox=Tkinter.Listbox(self.frame, bg='gray70')
        self.listbox.pack(side='top', padx=5, pady=5, expand='yes', fill='both')
        for i in tkFont.families():
            self.listbox.insert(Tkinter.END, i)

        # Frame in [ 0. mainframe]
        self.bold=ttk.Checkbutton(self.mainframe0, text='Bold', onvalue='bold', offvalue='normal', variable=self.var2)
        self.bold.pack(side='left',expand='yes', fill='x')
        self.italic=ttk.Checkbutton(self.mainframe0, text='Italic', onvalue='italic', offvalue='roman',variable=self.var3)
        self.italic.pack(side='left', expand='yes', fill='x')
        self.underline=ttk.Checkbutton(self.mainframe0, text='Underline',onvalue=1, offvalue=0, variable=self.var4)
        self.underline.pack(side='left', expand='yes', fill='x')
        self.overstrike=ttk.Checkbutton(self.mainframe0, text='Overstrike',onvalue=1, offvalue=0, variable=self.var5)
        self.overstrike.pack(side='left', expand='yes', fill='x')
        
        # Frame in [ 1. main frame]
        ttk.Entry(self.frame1, textvariable=self.var1).pack(side='top', padx=5, pady=5, expand='yes', fill='x')
        self.size=Tkinter.Listbox(self.frame1, bg='gray70')
        self.size.pack(side='top', padx=5, pady=5, expand='yes', fill='both')
        for i in range(30):
            self.size.insert(Tkinter.END, i)

        Tkinter.Label(self.mainframe1, bg='white',text='''
ABCDEabcde12345
''', font=self.font_1).pack(expand='no', padx=10,pady=10)

        # Frame in [ 2. mainframe]
        ttk.Button(self.mainframe2, text='   OK   ', command=out).pack(side='left', expand='yes', fill='x', padx=5, pady=5)
        ttk.Button(self.mainframe2, text=' Cancel ', command=end).pack(side='left', expand='yes', fill='x', padx=5, pady=5)
        ttk.Button(self.mainframe2, text=' Apply  ', command=applied).pack(side='left', expand='yes', fill='x', padx=5, pady=5)
        
        self.listbox.bind('<<ListboxSelect>>', checkface)
        self.size.bind('<<ListboxSelect>>', checksize)

After Above Step, Again Copy All The Codes Given Below And Save It In A Text File With Extension Py On The Same Directory  Because We Will Import Above Created Font Box Python Script. Here I Saved This Script As Testfont.Py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from fontbox import *
try:
    import Tkinter
except:
    import tkinter as Tkinter
import tkFont


root=Tkinter.Tk()
font1=tkFont.Font()
Tkinter.Text(root,font=font1).pack()
Font_wm(Font=font1)
root.mainloop()

Now, Run this script and you will see an Font chooser with live demo.
You can also upgrade this code as your need.
Now, Its Time To Understand How All This Works!
First of all, we need to import module. So, below codes are, To import module.

try:
    import Tkinter
except:
    import tkinter as Tkinter
# import module
import tkFont,ttk

In Second Part, I wrote a Tkinter Class object, so that we can use tkinter functionalities as object. Why? because it's looks more easy and give us more object oriented facilities and also, it's best practise to Use.

class Font_wm(Tkinter.Toplevel):
    def __init__(self, Font=None):

        Tkinter.Toplevel.__init__(self)
        self.mainfont=Font
        self.title('Font ...')

Basically, In Third Part, I am using Tkinter In Built StringVar And IntVar Variable Functionality To Make My Font Selection Window More Easy To Code. With StringVar or IntVar Object, You don't Need to keep track of created variable. In simple words, I am going to use These object like a communication pipe between functions. nothing else. actually, there are various methods are also available but i used this one, because hmm, I don't know.

        # Variable
        self.var=Tkinter.StringVar()# For Font Face
        self.var.set(self.mainfont.actual('family'))
        self.var1=Tkinter.IntVar()  # for Font Size
        self.var1.set(self.mainfont.actual('size'))
        self.var2=Tkinter.StringVar() # For Bold
        self.var2.set(self.mainfont.actual('weight'))
        self.var3=Tkinter.StringVar() # For Italic
        self.var3.set(self.mainfont.actual('slant'))
        self.var4=Tkinter.IntVar()# For Underline
        self.var4.set(self.mainfont.actual('underline'))
        self.var5=Tkinter.IntVar() # For Overstrike
        self.var5.set(self.mainfont.actual('overstrike'))

Now, time to add some sample. Come On! Friend it's not that hard.

        # Font Sample
        self.font_1=tkFont.Font()
        for i in ['family', 'weight', 'slant', 'overstrike', 'underline', 'size']:
            self.font_1[i]=self.mainfont.actual(i)

And, Here Come Another part of code, where all codes are Just Add Some More Functionalities, Functions, Tkinter Widget In my Font Window To Make it More Realistic.
Simple!!

       def checksize(event):
            try:
                self.var1.set(int(self.size.get(self.size.curselection())))
                self.font_1.config(family=self.var.get(), size=self.var1.get(), weight=self.var2.get(), slant=self.var3.get(), underline=self.var4.get(), overstrike=self.var5.get())
            except:
                pass            
        def applied():
            self.result=(self.var.get(), self.var1.get(), self.var2.get(), self.var3.get(), self.var4.get(), self.var5.get())
            self.mainfont['family']=self.var.get()
            self.mainfont['size']=self.var1.get()
            self.mainfont['weight']=self.var2.get()
            self.mainfont['slant']=self.var3.get()
            self.mainfont['underline']=self.var4.get()
            self.mainfont['overstrike']=self.var5.get()
        def out():
            self.result=(self.var.get(), self.var1.get(), self.var2.get(), self.var3.get(), self.var4.get(), self.var5.get())
            self.mainfont['family']=self.var.get()
            self.mainfont['size']=self.var1.get()
            self.mainfont['weight']=self.var2.get()
            self.mainfont['slant']=self.var3.get()
            self.mainfont['underline']=self.var4.get()
            self.mainfont['overstrike']=self.var5.get()
            self.destroy()
        def end():
            self.result=None
            self.destroy()

You Just need to spend some time in Understand What Actually Going in this code. And Boom! You Got it


Done!

Thanks For Support
Please, Feel Free To Leave A Comment If Our Article has Helped You.
Created By:
S.S.B
surajsinghbisht054@gmail.com

Share this

Related Posts

Previous
Next Post »