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

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()
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)
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
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 border
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)
  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.
Solution
List of 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


plus2net.com



Post your comments , suggestion , error , requirements etc here




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