Add style to Python tkinter button

PythonServer Side ProgrammingProgramming

Tkinter has great support for creating the GUI programs based on python. It offers different ways of styling a button on the Tkinter canvas based on its font, size, colour etc. In this article we will see how to apply style to specific buttons or all buttons in general on the canvas.

Applying to Specific Buttons

Lets consider the case when we have two buttons in the canvas and we want to apply some styling only to the first button. We use the W.TButton as part of the configuration along with the font and the foreground colour.

Example

from tkinter import *
from tkinter.ttk import *

# Set the canvas
canv = Tk()
canv.geometry('200x150')

#Create style object
sto = Style()

#configure style
sto.configure('W.TButton', font= ('Arial', 10, 'underline'),
foreground='Green')

#Button with style
btns = Button(canv, text='Welcome !',
      style='W.TButton',
      command=canv.destroy)
btns.grid(row=0, column=1, padx=50)

#Button without style
btnns = Button(canv, text='Click to Start !', command=None)
btnns.grid(row = 1, column = 1, pady = 10, padx = 50)

canv.mainloop()

Output

Running the above code gives us the following result −

Applying to All Buttons

It is a similar configuration as above except that it has Tbutton as its style which automatically applies to all the buttons on the canvas.

Example

from tkinter import *
from tkinter.ttk import *

canv = Tk()
canv.geometry('200x150')

#Create style object
sto = Style()

#configure style
sto.configure('TButton', font=
('calibri', 10, 'bold', 'underline'),
foreground='Green')
# button 1
btns = Button(canv, text='Welcome !',
      style='TButton',
      command=canv.destroy)

btns.grid(row=0, column=1, padx=50)

# button 2
btnns = Button(canv, text='Click to start !', command=None)
btnns.grid(row=1, column=1, pady=10, padx=50)

canv.mainloop()

Output

Running the above code gives us the following result −

raja
Published on 26-Aug-2020 06:20:57
Advertisements