Python Tkinter Button – How to use

In this Python tutorial, we will learn about Python tkinter button. Also we will see these topics.

  • Python Tkinter Button Command
  • Python Tkinter Button Styles
  • Python Tkinter Button Position
  • Python Tkinter Button size
  • Python Tkinter Button Color
  • Python Tkinter Button Shape
  • Python Tkinter Button Image
  • Python Tkinter Button Command Arguments
  • Python Tkinter Button Attributes
  • Python Tkinter Button Greyed Out

Tkinter Button Command

  • The button widget is used to place a button on the screen.
  • Button holds a functionality that is triggered when pressed.

Syntax:

In this syntax, ws is the master, in place of the text you can mention the purpose of the button, Function or method should be passed as command.

Button(ws, text="any text", command=function/method).pack()

.Code:

In this there is a subscribe button. When user clicks on that button, message box with thank you appears.

from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.title('PythonGuides')

def subscribe():
    return messagebox.showinfo('PythonGuides','Thnak you for subscribing!')

Button(ws, text="Subscribe", command=subscribe).pack(pady=20)


ws.mainloop()

Output:

As you can see in the below output screen. A soon as the user clicked on the subscribe button he gets a prompt. If you want to call the function just once then add (), after calling the function. Like in this example command=subscribe()

python tkinter button command
python tkinter button

Tkinter button Styles

  • Style is used to provide an improved look to buttons
  • It provides wide varieties of features like background, foreground, font, etc
  • A developer can prepare a template for designing a button
  • and using style it can be implemented on all the buttons
  • you can apply changes to a single button or multiple buttons

Code:

from tkinter import *
from tkinter.ttk import * 

ws = Tk()
ws.title('PythonGuides')
ws.geometry('200x200')

st = Style()
st.configure('W.TButton', background='#345', foreground='black', font=('Arial', 14 ))

Button(ws, text='Smash Me', style='W.TButton', command=None).pack()

ws.mainloop()

Output:

This output is implemented using style.

python tkinter button style
Tkinter button Styles

Tkinter Button Position

  • There are 3 layout managers: Pack, Grid, Place.
  • Pack is used to align widget in the center of the frame.
  • Grid uses row & column method of placing widgets.
  • Place is used to position widget in any coordinated provided as x & y

Syntax:

Button(ws, text="any text", command=function/method).pack()

Button(ws, text="any text", command=function/method).grid(row=value, column=value)

Button(ws, text="any text", command=function/method).place(x=value, y=value)

Code using pack:

from tkinter import *

ws = Tk()
ws.title("PythonGuide")
ws.geometry('200x250')

Button(ws, text="Click", command=None).pack()

ws.mainloop()

Output:

In this output, pack is used to place the button. Pack aligns the widget in the center. That is why when screen is resized in second picture, the button remains in the center position.

python tkinter button positioning using pack
Button positioning using pack

Code using grid:

from tkinter import *

ws=Tk()
ws.title("PythonGuide")
ws.geometry('200x250')

Button(ws,text="Click",command=None).grid(row=0, column=0)

ws.mainloop()

Output:

In this output, you can see that button is positioned at 0 row & 0 column that means top left side. In grid button remains in its position even if the window is resized.

python tkinter button grid
Tkinter Button Position

Code using place:

from tkinter import *

ws = Tk()
ws.title("PythonGuide")
ws.geometry('200x250')

Button(ws, text="Click", command=None).place(x=20, y=20)

ws.mainloop()

Output:

In this output, buttons are positioned using the place. The place provides maximum control. AS you can see 2 buttons are placed in different positions, but since the screen size is smaller than the position of the second button is so it not appearing. But when the screen is stretched it starts appearing.

python tkinter button place

Tkinter Button size

  • Resizing of button simple means increasing or decreasing the width & height of the button widget.
  • This can be easily done using keywords width and height.

Code:

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('200x200')

Button(ws, text='Smash Me!', height=10, width=20).pack(pady=10)

ws.mainloop()

Output:

In this output, button size has been increased from a regular one. The standard size of button is mentioned in the above section. In this case height and width of the button has been increased.

python tkinter button height width
Tkinter Button size

Tkinter Button Color

  • Colour plays an important role in making the application look attractive & eye-catchy.
  • Buttons can also be painted in any colour.
  • there are 2 sections that need to be colored.
  • first is the background of the button second is the font color
  • bg keyword is used to paint the background
  • fg keyword is used to color the font.

Code:

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('200x200')

Button(ws, text='Smash Me!', height=10, width=20, bg='#567', fg='White').pack(pady=10)

ws.mainloop()

Output:

In this output, background has been painted with blue and font colour is white. word & hexacode both are acceptable.

python tkinter button colour
Tkinter Button Color

Tkinter Button Shape

  • Shape refers to applying shape in the button
  • Shapes can be rectangular, oval, circle, etc.
  • Shapes are not supported in tkinter
  • You cannot create a rounded button directly from the widget.
  • to do so you need a rounded image.
  • And then reduce the border width to 0.
  • To see the demo refer to Tkinter image section

Tkinter Button Image

  • Images improve the look of an application
  • to apply an image on a button we use image keyword

Code:

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x200')   

dwnd = PhotoImage(file='download.png')
Button(ws, image=dwnd, command=None).pack(pady=10)

ws.mainloop()

Output:

In this output, the Download button image is applied to the button widget. And it is clickable which means it is a button. But this has a button background. To remove the button border set borderwidth = 0. In the next image you can see there is no border in that.

python tkinter button image
Button image with background
python tkinter button image with 0 width
Button image without background

Tkinter Button Command Arguments

  • Command button argument refers to providing input in the command button
  • In a calculator, the code takes a key argument through a button command.
  • Similarly, we will write code that will send a number to the function

Code:

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('200x200')

ep = ''
def keyLog(k):
    global ep
    ep = ep + str(k)
    actn.set(ep)

actn = StringVar()
Entry(ws, textvariable=actn).pack()

one_Btn = Button(ws, text='1', command=lambda: keyLog(1), padx=5, pady=5)
two_Btn = Button(ws, text='2', command=lambda: keyLog(2), padx=5, pady=5)
three_Btn = Button(ws, text='3', command=lambda: keyLog(3), padx=5, pady=5)

one_Btn.pack()
two_Btn.pack()
three_Btn.pack()

ws.mainloop()

Output:

So in this output, argument in the form of key name ie. 1 or 2 or 3 is passed to the function wherein these numbers are printed in the entry box.

python tkinter button command argument
Tkinter Button Command Arguments

Tkinter Button Attributes

  • Attributes are the properties of button widget
  • It holds list of all the features of widget
  1. activebackground & activeforeground
  • active background changes background colour of the button when clicked
  • activeforeground changes text color when button is clicked

Code:

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x200')   

Button(ws, text="Smash Me", activebackground='#345',activeforeground='white', padx=5, pady=5 ).pack(pady=10)

ws.mainloop()

Output:

In this output, the first image shows the button without click but the second image shows the change in background colour & text colour when clicked. It will become normal as soon as the button will be released

python tkinter button before & after click
Tkinter Button Attributes

2. colours:

  • colours plays an important role in software development.
  • Every colours has some meaning like red for error, green of correct, etc.
  • bg is used to fill background colour of the label
  • fg is used to change the text colour.
  • you can either provide a colour name or hex code

Example:

Button(ws, text="Click", bg="blue", fg="#000").pack()

3. font :

  • fonts make text readable.
  • to know more about fonts.

Example:

Button(ws, text="font", font=('arial bold', 18)).pack()

4. relief:

  • relief is used to provide decoration to the border.
  • It has various options that can be used to emphasize text.
  • Button border defines the type of border & its thickness.
  • There 6 types of borders each having their on property:
    • Flat
    • Raised
    • Sunken
    • ridge
    • solid
    • groove
  • By default flat is active.
  • borderwidth keyword is used to define the thickness of the border.
  • relief keyword is used to define the type of border.

Syntax: borderwidth should be provided any integer value, relief should provide anyone out of these ( flat, raised, sunken, ridge, solid, groove).

Label(ws, text="any text", borderwidth=value, relief="typeofborder").pack()

Code:

from tkinter import *

ws = Tk()
ws.title("Border")
ws.geometry("300x400")

Button(ws, text="Flat border", borderwidth=3, relief="flat", padx=5, pady=10).pack(padx=5, pady=10)
Button(ws, text="raised border", borderwidth=3, relief="raised", padx=5, pady=10).pack(padx=5, pady=10)
Button(ws, text="sunken border", borderwidth=3, relief="sunken", padx=5, pady=10).pack(padx=5, pady=10)
Button(ws, text="ridge border", borderwidth=3, relief="ridge", padx=5, pady=10).pack(padx=5, pady=10)
Button(ws, text="solid border", borderwidth=3, relief="solid", padx=5, pady=10).pack(padx=5, pady=10)
Button(ws, text="groove border", borderwidth=3, relief="groove",padx=5, pady=10).pack(padx=5, pady=10)

ws.mainloop()

Output:

In this output, all types of border are displayed, each have width of 3 pixels. padx & pady determines the extra space around the box.

Python Label border width

Example:

Button(ws, text="relief demo", borderwidth=3, relief='solid border').pack()

5. Height & Width:

  • Height determines the vertical dimension of the Button.
  • Width determines the horizontal dimension of the Button.

Example:

Button(ws, text="Height & width", height=5, width=10).pack()

6. padx & pady

  • padx adds empty space vertically
  • pady adds empty space horizontally
  • if they are used within the Button then they add extra space inside the box
  • if they are used in the positioning section (pack/grid/place) then add space outside the box.

Example: Inside the box

Button(ws, text="Smash Me", padx=10, pady=5).pack()

7. Justify:

  • Justify is used for alignment.
  • It works similar to anchor but has only three options
  • LEFT, CENTER, RIGHT

Example:

Button(ws, text="Smash Me", justify=CENTER).pack()

Python Tkinter Greyed Out Button

  • Python Tkinter button Greyed out means button is in disable state & it can’t be clicked.
  • This method is used when a developer doesn’t want the user to proceed without fulfilling the requirement.
  • Next time if you see accept terms and conditions option somewhere on a website or software try going through accepting it. You will notice that button is disabled & it is not clickable.
  • state method is used to switch between NORMAL or DISABLED state.
    • NORMAL: Button is clickable and is ready to trigger a function
    • DISABLED: Button is greyed out and can’t be clicked.

Syntax:

Button(ws, text="any-text", state=DISABLED).pack()

Code:

In this code, we have created a demonstration of button greyed out. There is a button that is in disabled state. When user will check on the checkbox then this button will turn into normal state.

from tkinter import * 

def activate_submit():
    if var.get()==1:
        btn['state']=NORMAL
    elif var.get()==0:
        btn['state']=DISABLED 
    else:
        print('something went wrong!')

ws = Tk()
ws.title("PythonGuides")
ws.geometry("400x300")
ws['bg']='#5d8a82'

var = IntVar()
cb = Checkbutton(
    ws, 
    text="Terms & conditions", 
    onvalue=1, 
    offvalue=0,
    variable=var,
    font=("time", 16),
    command=activate_submit,
    bg='#5d8a82'
    )
cb.pack(pady=50)

btn = Button(
    ws, 
    text="Register",
    command=None,
    state=DISABLED, 
    padx=20, 
    pady=10,
    relief=RAISED, 
    font=('times bold', 14)
)
btn.pack()

ws.mainloop()

Output:

In this output, you can see that in the first picture the button is greyed out or is disabled but as soon as user accepted the terms and conditions but is normal and clickable.

python tkinter button state

You may like the following Python tutorials:

In this tutorial we have learned Python Tkinter Button:

  • Python Tkinter Button Command
  • Python Tkinter Button Styles
  • Python Tkinter Button Position
  • Python Tkinter Button size
  • Python Tkinter Button Color
  • Python Tkinter Button Shape
  • Python Tkinter Button Image
  • Python Tkinter Button Command Arguments
  • Python Tkinter Button Attributes
  • Python Tkinter Button Greyed Out