Python Button Widget

A python button is a component that performs some action when clicked. These buttons are created as objects of Button class

Syntax:

CopiedCopy Code
b = Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue', activebackground='green', activeforeground='red')

We can also display an image on the button as: #first load the image into file1

file1 = PhotoImage(file="cat.gif")

#create a push button with image

b = Button(f, image=file1, width=150, height=100, bg='yellow', fg='blue', activebackground='green', activeforeground='red')

Button Click Event

Python Push Button Program With Event Handler

A Python program to create a push button and bind it with an event handler function.

CopiedCopy Code

from tkinter import * 
#method to be called when the button is clicked 
def buttonClick(self): 
   print('You have clicked me') 
#create root window 
root = Tk() 
#create frame as child to root window 
f = Frame(root, height=200, width=300) 
#let the frame will not shrink 
f.propagate(0) 
#attach the frame to root window 
f.pack() 
#create a push button as child to frame 
b = Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue', activebackground='green', activeforeground='red') 
#attach button to the frame 
b.pack() 
#bind the left mouse button with the method to be called 
b.bind("Button-1", buttonClick) 
#the root window handles the mouse click event 
root.mainloop()

Button with Bind Event handler

Python program to create a push button and bind it with an event handler function using command option
CopiedCopy Code

from tkinter import * 
class MyButton: 
   def __init__(self, root): 
   #create a frame as child to root window 
      self.f = Frame(root, height=200, width=300) 
   #let the frame will not shrink 
      self.f.propagate(0) 
   #attach the frame to root window 
      self.f.pack() 
   #create a push button as child to frame and bind it to
  #buttonClickmethod 
      self.b = Button(self.f, text='My Button', width=15, height=2, bg='yellow', fg='blue', activebackground='green', activeforeground='red', command=self.buttonClick) 
   #attach button to the frame 
      self.b.pack() 
   #method to be called when the button is clicked 
   def buttonClick(self): 
      print('You have clicked me') 
root = Tk() 
mb = MyButton(root) 
root.mainloop()