Python tkinter Button


Youtube Live session on Tkinter


This code we will add one button.
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())

Updating Label text on Click of a Button 🔝

Updating Label on Button click
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('300x100') # width and height of the window
my_w.title('www.plus2net.com') # adding a title

# adding a Label with some default text, this text to be changed. 
lb1 = tk.Label(my_w,  text='Welcome', width=15,bg='yellow',font=22 )  
lb1.grid(row=1,column=1,padx=10)

# On click of this button the text on above Label will change. 
bt1=tk.Button(my_w,text='Update', font=22,bg='lightgreen',
    command=lambda:lb1.config(text='plus2net',bg='lightblue'))
bt1.grid(row=1,column=2,padx=20,pady=20)

my_w.mainloop() # hold the window for user interaction  

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 🔝

By using config() method we can change the attributes of the button based on different Events.

Mouse enter and leave events of a button in a Tkinter Window
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("350x150")  # width x height of window
bt1=tk.Button(my_w,text='Submit',bg='yellow',font=18,width=20)
bt1.grid(row=0,column=0,padx=80,pady=50)
def my_upd():
    bt1.config(text='Welcome',bg='lightgreen')
    # write your code here 

#bt1.bind('<Enter>',lambda e:bt1.config(text='Welcome',bg='lightgreen'))
bt1.bind('<Enter>',lambda e:my_upd()) # Mouse Enter event
bt1.bind('<Leave>',lambda e:bt1.config(text='Thanks',bg='yellow'))
my_w.mainloop() # Keep the window open 
Mouse Enter & Leave event on a Button

Drag and Drop a button by using place layout
Tkinter Button click event and reading by cget() and configuration of option values changing state

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()
Tkinter Events
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()
Here is the code to toggle the text written over a button ( from + to - ).
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("400x200")  

def my_upd():
    w=b1.cget('text') # read the text written over the button
    if w=='+':
        b1['text']='-' # Update text option 
    else:
        b1.config(text='+') # update text option

font1=['Times',30,'bold']    # set the font style 
b1 = tk.Button(my_w, text='+', width=10,bg='yellow', font=font1,
	command=lambda: my_upd())
b1.grid(row=1,column=1,padx=20,pady=50) 

my_w.mainloop()

Button Methods flash() and invoke()

There are two methods, flash() and invoke()

invoke() method to Trigger events without Clicking the button 🔝

We can simulate the button click event by using invoke().

invoke(): Button Press event without Clicking

flash() : Drawing user attention 🔝

We can flash() the button by changing the colour from active to normal several times.

flash(): Blinking the Button to draw user attention

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

Adding a reset button

We can reset the counter value to 0 or we can reset the display to 0 but start from previous counter value.
One more button b2 is added to Reset the counter.
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

def my_reset():
    global count
    count=0
    b1.config(text='Count: 0')

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=50,pady=50)

#b2=tk.Button(my_w,text='Reset',width=7,command=lambda:b1.config(text='Count: 0'))
b2=tk.Button(my_w,text='Reset',width=7,command=lambda:my_reset())
b2.grid(row=0,column=1)
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

List of Button attributes and values 🔝

Tkinter Button list of options with values and updating values
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("600x300") # Width and height of the window

b1=tk.Button(my_w,text='Button1')
b1.grid(row=0,column=1,padx=20,pady=60)

print("Total Number of options : ",len(b1.keys())) # 35 

b1['bd']=10 # updating value of border width option to 10

for b in b1.keys():
    print(b,'=',b1[b]) # Option name and value 

my_w.mainloop()
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')
anchor
Alignment of font over the button.
values can be n, ne, e, se, s, sw, w, nw, or center
b1=tk.Button(my_w,text='B1',width=10,anchor='se')
background Background color of the button.
b1=tk.Button(my_w,text='My Button',width=10,background='green')
bitmap Display bitmaps on the button.
lb1=tk.Button(my_w,bitmap='question')
Other bitmaps are 'error', 'gray75', 'gray50', 'gray25', 'gray12', 'hourglass', 'info', 'questhead', 'question', and 'warning'
More on Tkinter Bitmap
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 active 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 (default), 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
  6. Manage the width of a button by changing value of a Spinbox.
Solution

Cursor shapes on Mouse hover 🔝

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
How Reset button is used to delete all user enterd data and selections
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-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer