Python tkinter Button

This code we will add one button.
Basics of Python Tkinter
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.grid(row=2,column=2) 

my_w.mainloop()
To manage layout read more on grid()

Tkinter Button adding style foreground background font boarder relief state

There are many optional options we can add to button, the list is available below.

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())

Enable Disable button

Enable Disable button by click event
We can enable or disable a button and manage the text over the button. Here is the code to disable or enable 2nd button by using 1st button. The text also changes based on status
import tkinter  as tk 
from tkinter import * 
my_w = tk.Tk()
my_w.geometry("400x250") 
b1 = tk.Button(my_w, text='Disable',command=lambda: my_fun())
b1.grid(row=1,column=1)

b2 = tk.Button(my_w, text='I am Enabled ', width=15)
b2.grid(row=1,column=2)

def my_fun():
    st=b2["state"]
    if(st=="normal"):
        b2["state"]="disabled"
        b2["text"]="I am Disabled"
        b1["text"]="Enable"
    else:
        b2["state"]="normal"
        b2["text"]="I am Enabled"
        b1["text"]="Disable"
my_w.mainloop()

Understanding Events

Tkinter Button click event and reading by cget() and configuration of option values changing state

By using config() method we can change attributes of the button. We will add one more button and on click of this button the colour of our Close button will change. Here is the code.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("500x500")  

def my_upd():
    b2.config(bg='red')
    
b1 = tk.Button(my_w, text='Change Color', width=50,bg='yellow',
  command=lambda: my_upd())
b1.grid(row=2,column=2) 

b2 = tk.Button(my_w, text='Close', width=20,
	bg='yellow',command=my_w.destroy)
b2.grid(row=2,column=3) 

my_w.mainloop()
By using above code we can change any attribute of a button, now we will learn how to read the attribute and then change the same.

Reading the attribute by using cget()

import tkinter as tk
my_w = tk.Tk()
my_w.geometry("600x200")  

def my_upd():
    w=b2.cget('width') # read the width of the button
    w=w+5              # increase width by 5 
    b2.config(width=w)
    
b1 = tk.Button(my_w, text='+', width=10,bg='yellow',
	command=lambda: my_upd())
b1.grid(row=1,column=1) 

b2 = tk.Button(my_w, text='Close', width=10,bg='red',
	command=my_w.destroy)
b2.grid(row=1,column=2) 

my_w.mainloop()

Counting Number of Clicks of a Button

Counting Number of Clicks and displaying on a button

We will count the number of clicks on a button and display the same value on the button.
import tkinter as tk
my_w = tk.Tk() # Parent window 
my_w.geometry("400x150")  # width and height 
count=0 # initial value of counter 

def my_upd():
    global count 
    count=count+1 # increase by 1
    b1.config(text='Count: '+str(count)) # update text
    
b1=tk.Button(my_w,text='Count: 0 ',width=12,
	command=lambda:my_upd(),bg='orange',font=12)
b1.grid(row=0,column=0,padx=100,pady=50)
my_w.mainloop()
Counting and displaying number of clicks on a button inside a Tkinter window


Validating inputs before activating the button

Tkinter manage state of a button to disable or enable based on number of char entered in Entry field


By using any Entry button user can enter data and we can ensure that minimum 5 chars are to be entered before the user is allowed to click the Button. We may extend this to multiple condition checking while using many inputs. Here is a simple code in which we are keeping the button in disabled condition ( state=’disabled’ ) as long as the user has entered minimum required chars in the input Entry box.
Disabled button
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('200x100')
my_str=tk.StringVar(my_w)
e1=tk.Entry(my_w,textvariable=my_str)
e1.grid(row=0,column=0)
b1=tk.Button(my_w,text='Button',state='disabled')
b1.grid(row=0,column=1)
def my_upd(*args):
    if(len(my_str.get())>4): # Minimum 5 char length
        b1.config(state='normal') # Enable the button 
    else:
        b1.config(state='disabled') # disable the button
my_str.trace('w',my_upd) # event listener 
my_w.mainloop()
Dynamic Buttons handling
activebackground
Active Background Color
Background Colour of the button when button is active or pressed
b1=tk.Button(my_w,text='MyButton',width=10,activebackground='red')
activeforeground
Foreground color ( font ) of the button when button is active or pressed.
b1=tk.Button(my_w,text='B1',width=10,activeforeground='green')
background Background color of the button.
b1=tk.Button(my_w,text='My Button',width=10,background='green')
bgSame as background
bd Same as borderwidth
b1=tk.Button(my_w,text='My Button',width=10,bg='yellow',bd=5)
To remove border from the button we can use bd=0. To remove the border onClick we can use config() to set the bd=0.
b1=tk.Button(my_w,text='Button',command=lambda:b1.config(bd=0))
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()
cursor
shape of the cursor when it is placed over the button. A list of cursor shapes are given below.
b1=tk.Button(my_w,text='My Button',width=10,cursor='boat')
default One extra border is added to ative button.

This can have two values active or normal

Out of two buttons My Button 2 ( right one ) is kept as active button.
b1=tk.Button(my_w,text='My Button',width=10)
b1.grid(row=1,column=1)
b2=tk.Button(my_w,text='My Button 2',width=10,default='active')
b2.grid(row=1,column=2)
default of a button

disabledforeground
The foreground colour when the button is disabled ( state='disabled')
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('200x100')
    
b1=tk.Button(my_w,text='I am Normal',width=10,\
state='normal' ,disabledforeground='red')
b1.grid(row=1,column=1)

b2=tk.Button(my_w,text='I am Disabled',width=10,\
state='disabled' ,disabledforeground='red')
b2.grid(row=1,column=2)

my_w.mainloop()
Disabledforeground of a button
font
Font size style of the button
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('200x100')
    
b1=tk.Button(my_w,text='My Button',width=10,font=18)
b1.grid(row=1,column=1)
my_w.mainloop()
We can use variable for type and style.
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('200x100')
my_font=('times', 8, 'underline')    
b1=tk.Button(my_w,text='My Button',width=10, font=my_font)
b1.grid(row=1,column=1)
my_w.mainloop()
fgSame as foreground
b1=tk.Button(my_w,text='My Button',width=10, fg='red')
heightHeight of the buttons ( We can manage size of the button by using height and width )
b1=tk.Button(my_w,text='My Button',width=10,height=3)

highlightbackground
Border color when the button is not in focus.
b1=tk.Button(my_w,text='B1',highlightbackground='red',bd=5)

highlightcolor
Border colour when the button is in focus.
b1=tk.Button(my_w,text='B1',width=10,highlightcolor='red',bd=5)

highlightthickness
Width of the border when highlighted
b1=tk.Button(my_w,text='B1',width=10,bd=5,highlightthickness=5)
imageImage we can display on the button
Read more on how to display image over a button
Images used over button to create ON / Off switch
Read more on how to disply MySQL Blob data using button
justifyAlign multiple line of text. It can be LEFT , RIGHT or CENTER
padx Horizontal padding between text and border
b1=tk.Button(my_w,text='B1',width=5,height=1, padx=20,pady=10)
pady Vertical padding between text and border
b1=tk.Button(my_w,text='B1',width=5,height=1,padx=20, pady=10)
reliefThe Button ( borders ) 3 D effect style.
It can take these values raised , sunken ,flat, ridge, solid & groove
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("250x200")  
l1 = tk.Label(my_w,text='Button relief' ) 
l1.grid(row=1,column=1) 

l1 = tk.Label(my_w,  text='Raised' ) #  
l1.grid(row=2,column=1) 

t1 = tk.Button(my_w,height=1,relief='raised')
t1.grid(row=2,column=2) 

l1 = tk.Label(my_w,text='sunken' ) # 
l1.grid(row=3,column=1) 

t1 = tk.Button(my_w,height=1,relief='sunken')
t1.grid(row=3,column=2)

l1 = tk.Label(my_w,text='flat' ) # 
l1.grid(row=4,column=1) 

t1 = tk.Button(my_w,height=1,relief='flat')
t1.grid(row=4,column=2)

l1 = tk.Label(my_w,text='ridge' ) 
l1.grid(row=5,column=1) 
t1 = tk.Button(my_w,height=1,relief='ridge')
t1.grid(row=5,column=2)

l1 = tk.Label(my_w,text='solid' ) # added one Label 
l1.grid(row=6,column=1) 
t1 = tk.Button(my_w,height=1,relief='solid')
t1.grid(row=6,column=2)

l1 = tk.Label(my_w,text='groove' ) # added one Label 
l1.grid(row=7,column=1) 

t1 = tk.Button(my_w,height=1,relief='groove')
t1.grid(row=7,column=2)

my_w.mainloop()
relief of a button
overrelief
Similar to relief ( as above ) but all effects
takes place when Mouse is over the button.
You can change the above code by using overrelief in place of relief
t1 = tk.Button(my_w,  width=10,height=1,overrelief='groove')
statevalues= normal, active or disabled
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('400x100')

b1=tk.Button(my_w,text='I am Active',state='active')
b1.grid(row=1,column=1)

b2=tk.Button(my_w,text='I am normal',state='normal')
b2.grid(row=1,column=2)

b3=tk.Button(my_w,text='I am Disable',state='disable')
b3.grid(row=1,column=3)

my_w.mainloop()
different state  of  buttons
takefocus : By using Tab you can shift the focus.
Value can be True or False.
By setting takefocus to False we can skip the focus while using tab.
Here the focus shifts between first and second button by skipping the third button
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('300x100')

b1=tk.Button(my_w,text='First',height=1,takefocus=True)
b1.grid(row=1,column=1)

b2=tk.Button(my_w,text='Second',height=1,takefocus=True)
b2.grid(row=1,column=2)

b3=tk.Button(my_w,text='Third',height=1,takefocus=False)
b3.grid(row=1,column=3)

my_w.mainloop()
textThe text written over the button
b1=tk.Button(my_w, text='First ',width=12,height=1)
textvariable We can use a variable to manage the text of a button.
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('200x100')

my_str=tk.StringVar()
b1=tk.Button(my_w, textvariable=my_str,width=25,height=1)
b1.grid(row=1,column=1)
my_str.set('I am from textvariable ')

my_w.mainloop()
underline Underline the Char given by the position. Here char B is underlined.
b1=tk.Button(my_w,text='MyButton',width=15,height=1,underline=3)
Underline char in a button
widthwidth of the button in Chars
b1=tk.Button(my_w,text='My Button', width=15,height=1)
wraplength When the text should be wrapped written over the button
b1=tk.Button(my_w,text='MyButton',width=15,
	height=3,wraplength=3)

Colourful Buttons by using images

colourful buttons in Tkinter window

Tkinter colourful buttons using image and background activebackground options to match window color


Change the main window background colour to match the button , here it is set to white ( #ffffff )
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("410x250")  # Size of the window 
my_w.configure(background='#ffffff') # white background for window
Set the border width to 0 ( bd=0 ) , background colour of button to white ( bg='#ffffff'). When button is pressed the background colour should match with window colour ( white here ) (activebackground='#ffffff'). With these setting use matching image to display as button. Change the path in below code to read the image file.
Here is the code.
my_img4 = tk.PhotoImage(file = "D:\\testing\\buttons\\b4.png") 
b4=tk.Button(my_w,image=my_img4,bd=0,bg='#ffffff',activebackground='#ffffff')
b4.grid(row=2,column=1,padx=10,pady=10)

Delete , hide and restore a Button

Delete hide and restore button
We can remove a button by using grid_forget(). Same can be restored by using grid(). To delete the button permanently we have to use destroy()
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("400x150")  

b1=tk.Button(my_w,text='Hide: \n grid_forget()',
    command=lambda:b4.grid_forget(),bg='orange',font=12)
b1.grid(row=0,column=0,padx=2,pady=10)
b2=tk.Button(my_w,text='Display : \n grid()',
    command=lambda:b4.grid(row=1,column=0,pady=10,
    padx=2,columnspan=3,sticky='ew'),bg='lightgreen',font=12)
b2.grid(row=0,column=1,padx=2,pady=10) 
b3=tk.Button(my_w,text='Destroy : \n destroy()',
    command=lambda:b4.destroy(),bg='orange red',font=12)
b3.grid(row=0,column=2,padx=2)

b4 = tk.Button(my_w, text='Hi Welcome', width=10,font=14,bg='yellow')
b4.grid(row=1,column=0,pady=10,padx=2,columnspan=3,sticky='ew') 
my_w.mainloop()
Download the zip file with sample button images and code here.
  1. Exercise on buttons
  2. Using the above concept keep two buttons one with + to increase the button width and other one is with – to decrease the width of the close button.
  3. Keep a set of ( say 6 ) buttons with different background colours. By clicking any button you can pass the same colour to Close button.
  4. Change in mouse cursor : By clicking respective button mouse over icons should change. Use one common function and receive different options as parameter. A list of accepted mouse options are available here.
  5. Based on the week number, display Yes or No on Click of a button
Solution
List of values for the cursor options can be used for cursor ( cursor=X_cursor ) when we place mouse over the button.
X_cursor
arrow
based_arrow_down
based_arrow_up
boat
bogosity
bottom_left_corner
bottom_right_corner
bottom_side
bottom_tee
box_spiral
center_ptr
circle
clock
coffee_mug
cross
cross_reverse
crosshair
diamond_cross
dot
dotbox
double_arrow
draft_large
draft_small
draped_box
exchange
fleur
gobbler
gumby
hand1
hand2
heart
icon
iron_cross
left_ptr
left_side
left_tee
leftbutton
ll_angle
lr_angle
man
middlebutton
mouse
pencil
pirate
plus
question_arrow
right_ptr
right_side
right_tee
rightbutton
rtl_logo
sailboat
sb_down_arrow
sb_h_double_arrow
sb_left_arrow
sb_right_arrow
sb_up_arrow
sb_v_double_arrow
shuttle
sizing
spider
spraycan
star
target
tcross
top_left_arrow
top_left_corner
top_right_corner
top_side
top_tee
trek
ul_angle
umbrella
ur_angle
watch
xterm
Dynamic Buttons handling
Images used over button to create ON / Off switch
Subscribe to our YouTube Channel here

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2022 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer