What is Tkinter? how to create Desktop application using Python, Python GUI

0

 


What is Tkinter?





It is the GUI  Library of python which provides a graphical user interface to develop a desktop application using python.


Tkinter is a light-weight open-source platform to develop products. Tkinter provides Widget to design form element(TextBox, Button, CheckBox, Radio, Window, Canvas, Multiple Window)


How to write code for Tkinter?


Tkinter by default integrates under Python Software Tools.


How to create Window using Tkinter


import tkinter as tk

window = tk.Tk()


How to add content on Windows?

import tkinter as tk

window = tk.Tk()

txt = tk.Label(text="welcome in tkinter")

txt.pack()   # it is used to bind label widget into window

window.mainloop()  # it create event loop to handle event


Label Widget:-

It is used to write content on Windows, we can use a different attribute to change color and background-color


label = tk.Label(

    text="Hello, Tkinter",

    foreground="white",  # Set the text color to white

    background="black"  # Set the background color to black

)

label.pack()



Complete Program to manage Label


import tkinter as tk

window = tk.Tk()

txt = tk.Label(text="welcome in tkinter")

txt.pack()

label = tk.Label(

    text="Hello, Tkinter",

    foreground="white",  # Set the text color to white

    background="black"  # Set the background color to black

)

label.pack()

label1 = tk.Label(

    text="Hello, Tkinter",

    fg="white",

    bg="black",

    width=10,

    height=10

)

label1.pack()

window.mainloop()



Button:-  It is used to manage event operations on a Tkinter window.


Program to display button on Tkinter

import tkinter as tk

window = tk.Tk()

button = tk.Button(

    text="Click me!",

    width=25,

    height=5,

    bg="blue",

    fg="yellow",

)

button.pack()


window.mainloop()



Entry Widget:-

It is used to create small textbox on python application, it provides lots of customization to input from the user's

  1. Retrieving text with .get()
  2. Deleting text with .delete()
  3. Inserting text with .insert()
Complete program to implement Entry Widget:-

import tkinter as tk
window = tk.Tk()

entry = tk.Entry(fg="yellow", bg="blue", width=50)
entry.pack()
button = tk.Button(
    text="Click me!",
    width=25,
    height=5,
    bg="blue",
    fg="yellow",
)
button.pack()

window.mainloop()

Window Text Mode:-

We can create Text Mode to the window where it will provide textbox similar to notepad and we can write content on it.


import tkinter as tk

window = tk.Text()

window.pack()

window.mainloop()


Frame in Tkinter:-

It is used to create a layout on the Tkinter window, using frame we can provide different partitions into python default window.


Program to create a frame in Tkinter:-


import tkinter as tk

window = tk.Tk()

frame_a = tk.Frame()

frame_b = tk.Frame()

label_a = tk.Label(master=frame_a, text="I'm in Frame A")

label_a.pack()

label_b = tk.Label(master=frame_b, text="I'm in Frame B")

label_b.pack()

frame_a.pack()

frame_b.pack()


How to manage different border using Tkinter frame:-

import Tkinter as tk


border_effects = {

    "flat": tk.FLAT,

    "sunken": tk.SUNKEN,

    "raised": tk.RAISED,

    "groove": tk.GROOVE,

    "ridge": tk.RIDGE,

}


window = tk.Tk()


for relief_name, relief in border_effects.items():

    frame = tk.Frame(master=window, relief=relief, borderwidth=5)

    frame.pack(side=tk.LEFT)

    label = tk.Label(master=frame, text=relief_name)

    label.pack()


window.mainloop()



place() in Tkinter:-

It is used to place a widget into a particular position of the window using x and y coordinate, x is for left and right and y is for top and bottom.

Code for place() under frame

import tkinter as tk

window = tk.Tk()

frame = tk.Frame(master=window, width=150, height=150)
frame.pack()

label1 = tk.Label(master=frame, text="SCS (0, 0)", bg="red")
label1.place(x=0, y=0)

label2 = tk.Label(master=frame, text="Label2 (75, 75)", bg="yellow")
label2.place(x=75, y=75)

window.mainloop()


grid() in frame:-

It is used to create a table view in the Tkinter application using the row index and column index.

row index and column index will be started from 0.


import tkinter as tk

window = tk.Tk()

for i in range(3):
    for j in range(3):
        frame = tk.Frame(
            master=window,
            relief=tk.RAISED,
            borderwidth=1
        )
        frame.grid(row=i, column=j)
        label = tk.Label(master=frame, text=f"Row {i}\nColumn {j}")
        label.pack()

window.mainloop()



Login Form Example in Tkinter using grid()


import tkinter as tk

window = tk.Tk()
window.geometry("300x250")
window.title("Login Form")
label1 = tk.Label(text="Enter username")
label1.grid(row=0,column=0)
txt = tk.Entry(text=" ",textvariable='uname')
txt.grid(row=0,column=1)
label2 = tk.Label(text="Enter password")
label2.grid(row=1,column=0)
txt2 = tk.Entry(text=" ",textvariable='pa')
txt2.grid(row=1,column=1)
btn = tk.Button(text="Login")
btn.grid(row=2,column=1)
window.mainloop()


.....................................................................................................................................................

Event operation in Tkinter:-

If we want to perform any action in Widget then we will use event-based programming.


 Tkinter uses the command attribute under button to manage an event. we will create an event method to writing functionality.

import tkinter as tk
def fun():
    print("hello world")
window = tk.Tk()
window.geometry("300x250")
window.title("Event Example")
frame = tk.Frame(master=window, width=150, height=150)
frame.pack()
btn = tk.Button(master=frame,text="click",command=fun)
btn.pack()

window.mainloop()


now the HelloWorld message is displayed on Console Screen but we want to display on the label widget.


Another good example of a tkinter to display text on a label after button click.

import tkinter as tk
def fun():
    lbl.config(text="hello world")
window = tk.Tk()
window.geometry("300x250")
window.title("Event Example")
frame = tk.Frame(master=window, width=150, height=150)
frame.pack()
btn = tk.Button(master=frame,text="click",command=fun)
btn.pack()
lbl = tk.Label(master=frame)
lbl.pack()

window.mainloop()


Now another example we will take text field, button, and label when we click then text field data should be displayed on the label.

import tkinter as tk
def fun():
    lbl.config(text=txt.get())   #txt.get() is used to get the text of entry widget
window = tk.Tk()
window.geometry("300x250")
window.title("Event Example")
frame = tk.Frame(master=window, width=150, height=150)
frame.pack()
txt = tk.Entry(master=frame)
txt.pack()
btn = tk.Button(master=frame,text="click",command=fun)
btn.pack()
lbl = tk.Label(master=frame)
lbl.pack()

window.mainloop()



WAP to calculate simple interest using Tkinter GUI Tools?

import tkinter as tk
def fun():
    p = txt1.get()
    r = txt2.get()
    t = txt3.get()
    si = (float(p)*float(r)*float(t))/100
    lbl.config(text="si is "+str(si))
window = tk.Tk()
window.geometry("300x250")
window.title("Event Example")
frame = tk.Frame(master=window, width=150, height=150)
frame.pack()
lblp = tk.Label(master=frame,text="Enter P")
lblp.pack()
txt1 = tk.Entry(master=frame)
txt1.pack()
lblr = tk.Label(master=frame,text="Enter R")
lblr.pack()
txt2 = tk.Entry(master=frame)
txt2.pack()
lblt = tk.Label(master=frame,text="Enter T")
lblt.pack()
txt3 = tk.Entry(master=frame)
txt3.pack()
btn = tk.Button(master=frame,text="click",command=fun)
btn.pack()
lbl = tk.Label(master=frame)
lbl.pack()

window.mainloop()



Create STOP Watch using Tkinter:-

import tkinter as tk

counter = 0 
def counter_label(label):
  counter = 0
  def count():
    global counter
    counter += 1
    label.config(text=str(counter))
    label.after(1000, count)
  count()
 
 
root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="dark green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()


Message widget:-  

It is similar to the Label widget, but it is used to display the content of an application using multiple lines. It provides more customization to show text.

import tkinter as tk

window = tk.Tk()
window.geometry("300x250")
window.title("Message Example")
s= "Whatever you do will be insignificant, but it is very important that you do it.\n(Mahatma Gandhi)"
msg = tk.Message(master=window,text=s)
msg.config(bg='lightgreen', font=('times', 24, 'italic'))
msg.pack()

window.mainloop()

 


RadioButton and CheckBox:-

for a single option, we will use the radio button and for multiple options, we will use a checkbox.

Example of radioButton:-


import tkinter as tk
root = tk.Tk()
root.geometry("300x250")
v= tk.IntVar()
def showcourse():
    if v.get()==1:
     lbl.config(text="Python")
    else:
      lbl.config(text="Pearl")  
     
    
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)
tk.Button(root,text="click",command=showcourse).pack()
lbl=tk.Label(root)
lbl.pack()




Example of Checkbox:-



import tkinter as tk
root = tk.Tk()
root.geometry("300x250")
v1= tk.IntVar()
v2= tk.IntVar()

def showcourse():
    s=''
    if v1.get()==1:
      s = s + "Python"
    if v2.get()==1:
      s=  s + "Pearl"  
    lbl.config(text=s)
   
     
    
tk.Checkbutton(root, 
              text="Python",
              padx = 20, 
              variable=v1
              ).pack(anchor=tk.W)
tk.Checkbutton(root, 
              text="Perl",
              padx = 20, 
              variable=v2
              ).pack(anchor=tk.W)
tk.Button(root,text="click",command=showcourse).pack()
lbl=tk.Label(root)
lbl.pack()


root.mainloop()



Text widget:-

It is used to show content into multiple lines similar to the textarea of HTML.

We will use insert() in textarea.


T.insert(tk.END, "Just a text Widget\nin two lines\n")

example:-
import tkinter as tk
window = tk.Tk()
window.geometry("300x250")
window.title("Event Example")
txt = tk.Text(master=window,height=100,width=200)
txt.pack()
txt.insert(tk.END,"Welcome in TextWidget of Django")
window.mainloop()



Dialog and messagebox:-

Tkinter provides a predefined dialog box to display information.

Tkinter provides a warning, info showinfo(), and error showerror() based message box to show result and a confirm box to show the confirmation message askyesno().



import tkinter as tk
from tkinter import messagebox as mb
window = tk.Tk()
window.geometry("300x250")
window.title("Event Example")
def answer():
    mb.showerror("Answer", "Sorry, no answer available") #alert box error

def callback():
    if mb.askyesno('Verify', 'Really quit?'):  #confirm box return true false
        mb.showwarning('Yes', 'Not yet implemented')  #alert box warning
    else:
        mb.showinfo('No', 'Quit has been cancelled')   #alert box info

tk.Button(text='Quit', command=callback).pack(fill=tk.X)
tk.Button(text='Answer', command=answer).pack(fill=tk.X)
tk.mainloop()



.......................................................................................................................................


Dialog box:-

It is used to display openfiledialig, colordialog, and savedialog box to perfom directory operation and change color operation into Tkinter application from the operating system.

Tkinter provides tkFileDialog to perform dialog operation.



Example of FileDialog:-

import Tkinter as tk
from Tkinter import file dialog as fd 

def callback():
    name= fd.askopenfilename() 
    print(name)
    
errmsg = 'Error!'
tk.Button(text='File Open', 
       command=callback).pack(fill=tk.X)
tk.mainloop()




Example of color dialog in Python:-


import tkinter as tk
from tkinter.colorchooser import askcolor                  
s= "red"
def callback():
    global s
    result = askcolor(color="#6A9662", 
                      title = "Bernd's Colour Chooser")
    s=result[1]
    btn.config(fg=s)
    print(s)
    
root = tk.Tk()
btn=tk.Button(root, 
          text='Choose Color', 
          fg=s, 
          command=callback)
btn.pack(side=tk.LEFT, padx=10)
tk.Button(text='Quit', 
          command=root.quit,
          fg="red").pack(side=tk.LEFT, padx=10)
tk.mainloop()






The slider is Tkinter:- 

It is used to scroll up and scroll down screen based on the range;

It provides range-based value, suppose we want to provide range based UI development then we can use  Slider in Tkinter.



Example of Slider in Tkinter:-


from Tkinter import *

master = Tk()

def show_values():
    print (w1.get(), w2.get())

w1 = Scale(master, from_=0, to=42)
w1.pack()
w2 = Scale(master,from_=0, to=200, length=600,tickinterval=10, orient=HORIZONTAL)
w2.pack()
Button(master, text='Show', command=show_values).pack()
mainloop()



Menu Control in Tkinter:-

It is used to provide navigation options in Tkinter Windows Forms.

Tkinter provides a  Menu Width to create a menu and Submenu both.

menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)


from tkinter import *
from tkinter.filedialog import askopenfilename

def NewFile():
    print("New File!")
def OpenFile():
    name = askopenfilename()
    print(name)
def About():
    print("This is a simple example of a menu")
    
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=NewFile)
filemenu.add_command(label="Open...", command=OpenFile)
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...", command=About)

viewmenu = Menu(menu)
viewmenu.add_cascade(label="View", menu=viewmenu)
viewmenu.add_command(label="View...", command=vit)

mainloop()



How to navigate from one Window to another Window?

Tkinter provides only one mainloop() at a time hence we will create a Single Window Application with Multiple Child Window to create a complete application.

It provides toplevel() to show the child window under parent window.


Now I am providing an example to create a login and registration form under Tkinter.


from tkinter import * 
from tkinter.ttk import *
  
# creates a Tk() object 
master = Tk() 
  
# sets the geometry of main  
# root window 
master.geometry("500x500") 
  
  
# function to open a new window  
# on a button click 
def login(): 
      
    # Toplevel object which will  
    # be treated as a new window 
    newWindow = Toplevel(master) 
  
    # sets the title of the 
    # Toplevel widget 
    newWindow.title("New Window") 
  
    # sets the geometry of toplevel 
    newWindow.geometry("400x400") 
  
    # A Label widget to show in toplevel 
    Label(newWindow,  
          text ="This is a new window").pack() 


def reg():
    newWindow = Toplevel(master) 
  
    # sets the title of the 
    # Toplevel widget 
    newWindow.title("New Window") 
  
    # sets the geometry of toplevel 
    newWindow.geometry("400x400") 
  
    # A Label widget to show in toplevel 
    Label(newWindow,  
          text ="Registration Form").pack() 
  
label = Label(master,  
              text ="This is the main window") 
  
label.pack(pady = 10) 
  
# a button widget which will open a  
# new window on button click 
btn = Button(master,  
             text ="Login",  
             command = login) 
btn.pack(pady = 10) 
btn = Button(master,  
             text ="Register",  
             command = reg) 
btn.pack(pady = 10) 
    
# mainloop, runs infinitely 
mainloop() 



Now we create a new window program  using class and Object implementation 

from tkinter import * 
from tkinter.ttk import *
  
  
class NewWindow(Toplevel): 
      
    def __init__(self, master = None): 
          
        super().__init__(master = master) 
        self.title("New Window") 
        self.geometry("200x200") 
        label = Label(self, text ="This is a new Window") 
        label.pack() 
  
  
# creates a Tk() object 
master = Tk() 
  
# sets the geometry of  
# main root window 
master.geometry("200x200") 
  
label = Label(master, text ="This is the main window") 
label.pack(side = TOP, pady = 10) 
  
# a button widget which will 
# open a new window on button click 
btn = Button(master,  
             text ="Click to open a new window") 
  
# Following line will bind click event 
# On any click left / right button 
# of mouse a new window will be opened 
btn.bind("<Button>",  
         lambda e: NewWindow(master)) 
  
btn.pack(pady = 10) 
  
# mainloop, runs infinitely 
mainloop() 





How to connect Tkinter application to MySQL database:-

step first download MySQL Connector for Python to MYSQL Server.

https://dev.mysql.com/downloads/connector/python/

mysql-connector-python-8.0.20-windows-x86-64bit

the query for data selection to MySQL:-


import tkinter as tk 
import mysql.connector 
from tkinter import *


def submitact(): 
user = Username.get() 
passw = password.get() 

print(f"The name entered by you is {user} {passw}") 

logintodb(user, passw) 


def logintodb(user, passw): 
# If paswword is enetered by the 
# user 
if passw: 
db = mysql.connector.connect(host ="localhost", 
user = user, 
password = passw, 
db ="php12batch") 
cursor = db.cursor() 
# If no password is enetered by the 
# user 
else: 
db = mysql.connector.connect(host ="localhost", 
user = user, 
db ="php12batch") 
cursor = db.cursor() 
# A Table in the database 
savequery = "select * from STUDENT"
try: 
cursor.execute(savequery) 
myresult = cursor.fetchall() 
# Printing the result of the 
# query 
for x in myresult: 
print(x) 
print("Query Excecuted successfully") 
except: 
db.rollback() 
print("Error occured") 


root = tk.Tk() 
root.geometry("300x300") 
root.title("DBMS Login Page") 

C = Canvas(root, bg ="blue", height = 250, width = 300) 

# Definging the first row 
lblfrstrow = tk.Label(root, text ="Username -", ) 
lblfrstrow.place(x = 50, y = 20) 

Username = tk.Entry(root, width = 35) 
Username.place(x = 150, y = 20, width = 100) 

lblsecrow = tk.Label(root, text ="Password -") 
lblsecrow.place(x = 50, y = 50) 

password = tk.Entry(root, width = 35) 
password.place(x = 150, y = 50, width = 100) 

submitbtn = tk.Button(root, text ="Login", 
bg ='blue', command = submitact) 
submitbtn.place(x = 150, y = 135, width = 55) 

root.mainloop() 



The query for data insertion:-

import tkinter as tk 
import mysql.connector 
from tkinter import *
mydb = mysql.connector.connect( 
  host = "localhost", 
  user = "root", 
  database = "php12batch"
)  
mycursor = mydb.cursor() 
sql = "INSERT INTO `student` (`rno`, `name`, `branch`, `fees`, `mobile`) VALUES (%s,%s,%s,%s,%s);"
val = ("1234", "xyz","CS","12000","981233444") 

mycursor.execute(sql, val) 
mydb.commit() 

print(mycursor.rowcount, "details inserted") 

# disconnecting from server 
mydb.close() 


.......................................................................................................................................................

How to show an image into the Tkinter window?

install PIL means Python Image Library

Command to install pillow is:-

pip install pillow


Complete Code to Show Image:-

from tkinter import *
from PIL import Image, ImageTk
master = Tk() 
master.geometry("400x400") 
load = Image.open("1.jpg")
image = load.resize((450, 350), Image.ANTIALIAS)
render = ImageTk.PhotoImage(load)
img = Label(master, image=render)
#img.image = render
img.pack()

mainloop()



How to create set up:-



First, run this command 

pip install cx_freeze


Write the following code to represent Script:-





import sys
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"includes": ["tkinter"]}

# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(
    name = "simple_Tkinter",
    version = "0.1",
    description = "Sample cx_Freeze Tkinter script",
    options = {"build_exe": build_exe_options},
    executables = [Executable("the timer.py", base = base)])

setup(  name = "guifoo",
        version = "0.1",
        description = "My GUI application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("guifoo.py", base=base)])


After creating this go into the command prompt under project directory

and write the following command

python  setup.py install 









Tags

Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)