Tkinter Button

The Button class in tkinter module is used for interaction purpose. Button can contain text and image both like Label in tkinter. When a button is pressed by mouse click, some action can perform. The example of button below show button with text and button with image also.

from tkinter import *
win=Tk()
win.geometry('200x200')
b1=Button(win,text="Click Here")
b1.grid(row=0,column=0)
win.mainloop()

Above button example in tkinter show you text “Click Here” on Button

Button With Text in Tkinter

from tkinter import *
win=Tk()
win.geometry('250x250')
b1=Button(win,text="Red Text",fg = "red")
b1.grid(row=0,column=0)
b2=Button(win,text="Green Text",fg="green")
b2.grid(row=0,column=1)
b3=Button(win,text="blue Text",fg="blue")
b3.grid(row=1,column=0)
b4=Button(win,text="Yellow Text",fg="yellow")
b4.grid(row=1,column=1)
win.mainloop()
Button with Text in different Color Example

Image Button in Tkinter

from tkinter import *
win=Tk()
win.geometry('200x200')
img=PhotoImage(file="image-button.png")
b=Button(win,image=img,width=100,height=100)
b.grid(row=2,column=2)
win.mainloop()
Button with Image in Tkinter, Image and code should be in same project folder.

Quit Button in Tkinter

from tkinter import *
win=Tk()
win.geometry('200x200')
b1=Button(win,text="Quit Window",command=quit)
b1.grid(row=0,column=0)
win.mainloop()
Whenever you click on button, window will close itself.

Call Function on Mouse Click

from tkinter import *
#creating function to call on mouse click of b1 Button
def func():
    print("Hello Coder")

win=Tk()
win.geometry('200x200')
b1=Button(win,text="Print",command=func)
b1.grid(row=0,column=0)
b2=Button(win,text="Quit Window",command=quit)
b2.grid(row=0,column=1)
win.mainloop()
User define function call on mouse click

In the above code, you can create a function and call on mouse click of button. When you press Print button it output screen will show Hello Coder as output.