Everyone who has used a computer or even a phone or tablet know what a button is in a Graphical User Interface (GUI). A button is a clickable object that causes something to happen or start processing.
In this article, we can cover buttons on Tkinter. Keep in mind that if you have read the article on Labels, then most of this you should know since most options are the same for almost all widgets.
Text
The string used for the ‘text’ option is displayed on the button. Let’s look at a line of code:
Of course, you can have multiple buttons, each with different/same text.
TextVariable
Instead of using a literal string to signify the text on a button, we can use a variable to represent the text.
To start, you create the variable and then give it a value:
We initialize the variable in the first line using ‘StringVar()’ and naming the variable ‘buttontext’. In the second line, we ‘set’ a string value for the new variable. In the last line, we assign the variable to the button using ‘textvariable’ instead of ‘text’.
Command
Since a user can interact with a button, such as being clicked, we need to set what happens after a click occurs.
We create a function with the code for when the user clicks the button and we define the function name for the ‘command’ option:
Let’s look at an example:
So, let’s look at this a little closer.
For a second, let’s skip the function named ‘clicked’. The first line you come to that may not be familiar with other examples we’ve done is ‘count1 = 0’. The variable ‘count1’ will hold our counter. We increment number every time the user clicks the button.
You should notice that the button (b1) has the option set ‘command=clicked’ which coincides with the function ‘def clicked()’.
Now, everything seems to happen in the function, so let’s look at it now.
The first thing is to define that ‘count1’ is a global variable. So now we can use the count variable in the key code or in the function.
The next line is to increment the variable ‘count’ by ‘1’.
The last line in the function, ‘l1['text'] = "You pressed the button " + str(count1)+ " times."’, is to place the specified text and counter into the ‘l1’ (label) ‘text’ option.
So, every time we press the button, the code updates the label’s text with the counter to change it.
This gives you a basic idea of programming objects.
Lambda
You may have noticed that when we call a function from a button click, or other event, we do not use parenthesis or pass any arguments. If we try to pass arguments, it does not process the arguments properly and the parenthesis cause issues. So, how do we pass arguments to a function called by an event?
We use the ‘lambda’ keyword to get around this issue.
So, let’s assume we had two buttons on the window. We want each button to perform similar tasks that we can accomplish with one function, but we need to have some unique items processed for each button differently.
We create the buttons like this:
Here, you can see that we are calling lambda through the command and passing the function name, ‘clicked’, along with an argument of “1” or “2” depending on the button being pressed. Notice too that we pass the argument in parenthesis, so the function ‘clicked’ needs to handle this:
Here, you can see how it places the argument passed into the variable ‘number’. We can the test the value of ‘number’ to see which button the user presses.
You can pass as many arguments as you wish, as long the number of arguments in the defined function matches the number of arguments passed through lambda.
Foreground and Background
The foreground and background refer to the colors of each. The foreground color is the color of the text, while the background color is the color of the area of the button that is not text or a ‘relief’.
For foreground color, we use the parameter ‘fg’ and background is ‘bg’.
We have two methods to specify a color. We can use a name or specify a hexadecimal value.
The basic color names are:
By using a hexadecimal value, you can control the amount of the three basic colors (for light) of Red-Green-Blue. The values are hexadecimal from the least amount, 0 [00], to the most, 255 [FF].
So Yellow is a mix of Red and Green, which would be ‘#FFFF00’. This shows that there is full Red [FF] and full Green [FF] and no Blue [00]. We can set the background to ‘green’:
You can see that you can mix the use of hex and color names.
Font
You can set the font, size and style as needed.
The fonts are those installed on your system. If you plan on using the code on another system, make sure that any fonts you use that may have not been a pre-installed font with the Operating System (OS) is also copied over and installed in the OS.
We specify the font name with the code:
You can specify a size for the font by adding a comma and then set the size:
Keep in mind that as the font gets larger, the button will grow to accommodate the text to fit in the button.
If you want, you could change the font, size and style for each object that has a text option.
Now, for styles. The styles are:
FIGURE 1
Again, these can be combined to format your font the way you want it.
Justify
It may not be common, but if you have a button with multiple lines, they can be justified:
FIGURE 2
You should notice that the longest line is set as the text width for all lines and the smaller lines are justified by the longest one.
Height and Width
Similar to the ‘height’ and ‘width’ of labels, we can control the height and width of a button. Keep in mind that the value given is in characters, not pixels.
So, let’s expand on what we’ve done so far. We can have code that will use two buttons. One button will change the height and the second will change the width of a third button. The third button has no function but to show the use of the height and width option.
Here, we have a button, named ‘b1’ that, when clicked, changes the height of button 3, named ‘b3’. The change is caused by a change in the global variable ‘counth’. Button 2, named ‘b2’, causes the variable named ‘countw’ to increment when pressed.
Notice too that both are calling the same function, but using an argument to specify which button is being pressed. After determining which button the user presses, it increments the variable. After this process, Button 3, named ‘b3’, is changed by the height and width or the new values of the variable, no matter which button the user clicks.
I’m hoping another example of ‘lambda’ helps show how to use it.
Anchor
We can anchor text to a specific area of the object. Similar to justify where you need multiple lines of text, in this case, you need multiple lines for the object. If the object only has a single line, the anchor does very little.
The anchor lets you specify a side of the button, or the center:
FIGURE 3
Relief, OverRelief and BorderWidth
If you read the article on Labels, you may remember that the default border width for a Label is ‘0’. For a button, it is system specific and will either be ‘1’ or ‘2’. The Borderwidth is the amount of pixels around a button that are considered a ‘border’. The border can have a different color if needed.
The border is outside of the ‘relief’. The ‘relief’ is the style of ‘border’. Keep in mind that the ‘border’ you set actually outside of the ‘relief’. There are six different ‘reliefs’:
FIGURE 4
An example of setting the relief to ‘flat’ is:
The option ‘overrelief’ is used to change the ‘relief’ of a button when the cursor hovers over the button. Do not confuse this with the ‘click’ event. This occurs when the cursor passes over or stops on a button. With any of the buttons, it will change color when the cursor hovers over it, but you can change the default.
The BorderWidth lets you override the default width of the border. The default is 1 or 2 depending on the Operating System. An example shows a normal button and one with a ‘borderwidth’ of 5 followed by the output in Figure 5:
FIGURE 5
Style
The style setup is used to apply for specific button widgets (W.TButton) or to all buttons (Tbutton).
‘Tbutton’ is the name used for buttons. The ‘style’ is a ‘ttk’ option and reauires ‘ttk’ to be imported:
Now that ‘ttk’ is imported into the code, we can use ‘style’.
After loading ‘ttk’, we must initialize the Style option:
The ‘styleinit1’ variable can be any valid variable name. We then use the same variable name to configure the style:
We can use the name ‘W.Tbutton’ to specify which buttons will gain this style. You can change the ‘W’ if you want to set up multiple styles, such as ‘B1.Tbutton’, ‘B2.Tbutton’, etc.
To specify which button(s) to assign this style, we use the option ‘style=‘W.Tbutton’’ for the button:
If we want all buttons to be the same, or just the ones not given another style, we just specify ‘TButton’:
You can add as many options to the Style. Sometimes, you may set a specific style for all buttons, and when you add a button, all you need to specify is the text:
Even though we specify no style, it uses the default setup. This makes sure all buttons, with no style set, have the same appearance and you do not need to type all options for each button.
Underline
With this option, we can underline a letter on a button. This can help when setting up key bindings, so when the user presses special shortcut keys, it is as if the user clicks a button.
The default underlined character is ‘-1’ which is not one character in the text. The first character in the text is ‘0’ and so on.
An example is to underline the first letter for Button 1:
Once we bind the ‘ALT+b’ keystroke, we can set it to run ‘clicked’ just as if the user presses it by the mouse.
I will not get into ‘Bindings’ in this article, but should be in the next article.
WrapLength
By default, a button will grow to contain all the text you specify. By setting the ‘wraplength’, in pixels, you can make sure all buttons have the same width.
Just specify the option ‘wraplength=’ and set the number of pixels. The following code has its output shown in Figure 6:
FIGURE 6
You can see that the second button cuts off words to continue it on the next line. You may need to play with the numbers to get a button to look right.
Padding
Padding allows us to add space around the text in a button.
We can pad the area to the left and right of the text with the option ‘padx’, or above and below the text with ‘pady’. You can also pad both ‘padx’ and ‘pady’ together as well. The value given to the option is based in pixels.
Let’s look at an example with the output in Figure 7:
FIGURE 7
TakeFocus
If there are multiple widgets in the window, we can use the TAB key to switch between the objects. An object that is currently ‘selected’ by the TAB key has focus. For a widget to be on the list that can be selected by the TAB key, it must be allowed to ‘takefocus’. Most objects will ‘takefocus’ by default, the buttons are a good example. Any widget that can interact with the user usually ‘takefocus’. If you look back at labels, these do not ‘takefocus’ by default.
You can disable the ability by a button to ‘takefocus’ by:
If you want an object, such as a button named ‘b1’, to ‘takefocus’ you can:
If a button has focus, then it will be surrounded by a black line, as in Figure 8.
FIGURE 8
Here, see that ‘Button 1’ has focus.
When a button has focus, it has a black highlight that you can change.
HighlightColor, HighlightBackground and HighlightThickness
If a button has the focus, the default ‘highlightcolor’ is black.
When a button does not have focus, you can set the ‘highlightbackground’.
The highlighted box has a specific thickness of 1 or 2 depending on the Operating System. You can change the background thickness with the option ‘highlightthickness’.
Let’s have an example. I’ll make six buttons. The even buttons will have a ‘highlightbackground’ of ‘red’ and the odd ones will be ‘blue’. The ‘highlightcolor’ will be purple. Buttons 5 and 6 will have a thickness of 4 while the rest are the default.
The code is followed by the output in Figure 9:
FIGURE 9
ActiveForeground, ActiveBackground and DisabledForeground
An object has three states. Those states are:
FIGURE 10
These are the default colors for the state being ‘active’ or ‘disabled’. You can set your own with the options:
Cursor
If you should move the cursor over a button, you can change the cursor that is seen by a user. You can look at the article for Labels (Python 17 - Labels) to see the list. Use one of these cursor types for a button. The cursor reverts when it is no longer over the button.
An example is to make the cursor an ‘X’ when it moves over the button:
Image
Instead of having text in a button, we can place an image in it. There are two types of options:
First, you need to load the image and then use the loaded image as a button:
Remember that the path to the image is case-sensitive. Also, if you have a large image, the button will resize to match the image size.
You can omit the path to the image file if the image is in the same folder as the python code.
Compound
If we wanted, we can put text and an image in a button. By using both, this is a ‘compound’.
There are five different parameters for ‘compound’:
Example code is:
The output is shown in Figure 11.
FIGURE 11
Bitmap
We can use built-in bitmap images for the buttons. There are ten different images:
FIGURE 12
In the output, I added labels for each line. Any ‘text’ you specify for the button is ignored. It is possible to use ‘foreground’ and ‘background’ colors, so it is not plain gray.
You can use your own BMP files, but you need to convert them to XBM files, which are monochrome. Sample code is:
Here, the ‘tux1.xbm’ file is in the same folder as the Python file.
Invoke
When using the ‘invoke’ command, we can cause a button’s command function to be called without the user actually clicking on the button.
Say, for example, we have a button named ‘b1’. We can programmatically cause it to be pressed by using the command ‘b1.invoke()’ and the function listed with the ‘command’ option will be executed.
Flash
Using the ‘flash’ option will cause the button to be redrawn as it alternates between a ‘normal’ and ‘active’ state.
You can specify ‘active colors to change the flashing colors. When it is done flashing, it goes back to a ‘normal’ state.
An example of the command is:
Conclusion
Hopefully, this gets you working well with buttons in tkinter in Python.
Having Buttons will give you the possibility of more interaction with your programs.
In this article, we can cover buttons on Tkinter. Keep in mind that if you have read the article on Labels, then most of this you should know since most options are the same for almost all widgets.
Text
The string used for the ‘text’ option is displayed on the button. Let’s look at a line of code:
Code:
b1 = Button(text="Button 1")
Of course, you can have multiple buttons, each with different/same text.
TextVariable
Instead of using a literal string to signify the text on a button, we can use a variable to represent the text.
To start, you create the variable and then give it a value:
Code:
buttontext=StringVar()
buttontext.set("Button 1")
b1 = Button(textvariable=buttontext)
We initialize the variable in the first line using ‘StringVar()’ and naming the variable ‘buttontext’. In the second line, we ‘set’ a string value for the new variable. In the last line, we assign the variable to the button using ‘textvariable’ instead of ‘text’.
Command
Since a user can interact with a button, such as being clicked, we need to set what happens after a click occurs.
We create a function with the code for when the user clicks the button and we define the function name for the ‘command’ option:
Code:
button = Button(text”Button_text”,command=clicked_function)
Let’s look at an example:
Code:
from tkinter import *
def clicked():
global count1
count1 += 1
l1['text'] = "You pressed the button " + str(count1)+ " times."
root = Tk()
root.title('Button')
root.geometry("400x800")
for row in range(0,9):
root.grid_rowconfigure(row, weight=1)
for col in range(0,3):
root.grid_columnconfigure(col, weight=1)
count1 = 0
l1 = Label(text="You pressed the button 0 times.")
b1 = Button(text="Button 1",command=clicked)
b1.grid(column=1, row=0)
l1.grid(column=1, row=1)
root.mainloop()
So, let’s look at this a little closer.
For a second, let’s skip the function named ‘clicked’. The first line you come to that may not be familiar with other examples we’ve done is ‘count1 = 0’. The variable ‘count1’ will hold our counter. We increment number every time the user clicks the button.
You should notice that the button (b1) has the option set ‘command=clicked’ which coincides with the function ‘def clicked()’.
Now, everything seems to happen in the function, so let’s look at it now.
The first thing is to define that ‘count1’ is a global variable. So now we can use the count variable in the key code or in the function.
The next line is to increment the variable ‘count’ by ‘1’.
The last line in the function, ‘l1['text'] = "You pressed the button " + str(count1)+ " times."’, is to place the specified text and counter into the ‘l1’ (label) ‘text’ option.
So, every time we press the button, the code updates the label’s text with the counter to change it.
This gives you a basic idea of programming objects.
Lambda
You may have noticed that when we call a function from a button click, or other event, we do not use parenthesis or pass any arguments. If we try to pass arguments, it does not process the arguments properly and the parenthesis cause issues. So, how do we pass arguments to a function called by an event?
We use the ‘lambda’ keyword to get around this issue.
So, let’s assume we had two buttons on the window. We want each button to perform similar tasks that we can accomplish with one function, but we need to have some unique items processed for each button differently.
We create the buttons like this:
Code:
b1 = Button(text="Button 1",command=lambda: clicked("1"))
b2 = Button(text="Button 2",command=lambda: clicked("2"))
Here, you can see that we are calling lambda through the command and passing the function name, ‘clicked’, along with an argument of “1” or “2” depending on the button being pressed. Notice too that we pass the argument in parenthesis, so the function ‘clicked’ needs to handle this:
Code:
def clicked(number):
#common code for all buttons
if number == "1":
#code specifically for Button 1
elif number == "2":
#code specifically for Button 2
#more code for all buttons
Here, you can see how it places the argument passed into the variable ‘number’. We can the test the value of ‘number’ to see which button the user presses.
You can pass as many arguments as you wish, as long the number of arguments in the defined function matches the number of arguments passed through lambda.
Foreground and Background
The foreground and background refer to the colors of each. The foreground color is the color of the text, while the background color is the color of the area of the button that is not text or a ‘relief’.
For foreground color, we use the parameter ‘fg’ and background is ‘bg’.
We have two methods to specify a color. We can use a name or specify a hexadecimal value.
The basic color names are:
- black
- white
- red
- green
- blue
- purple
- green
- yellow
- orange
- and others….
Code:
b1=Button(text=”Button 1”, fg=‘white’,bg=‘purple’)
By using a hexadecimal value, you can control the amount of the three basic colors (for light) of Red-Green-Blue. The values are hexadecimal from the least amount, 0 [00], to the most, 255 [FF].
So Yellow is a mix of Red and Green, which would be ‘#FFFF00’. This shows that there is full Red [FF] and full Green [FF] and no Blue [00]. We can set the background to ‘green’:
Code:
b1 = Button(text='Button Color', fg='#ffff00', bg='green')
You can see that you can mix the use of hex and color names.
Font
You can set the font, size and style as needed.
The fonts are those installed on your system. If you plan on using the code on another system, make sure that any fonts you use that may have not been a pre-installed font with the Operating System (OS) is also copied over and installed in the OS.
We specify the font name with the code:
Code:
b1=Button(text=‘Button 1’,font=(‘ubuntu’))
You can specify a size for the font by adding a comma and then set the size:
Code:
b1=Button(text=‘Button 1’,font=(‘z003’,21))
Keep in mind that as the font gets larger, the button will grow to accommodate the text to fit in the button.
If you want, you could change the font, size and style for each object that has a text option.
Now, for styles. The styles are:
- weight - thickness (NORMAL or BOLD)
- slant - slant (ROMAN or ITALIC)
- underline - underline
- overstrike - strikeout
Code:
b1 = Button(text='Normal',font=('z003',22))
b2 = Button(text='Bold',font=('z003',22,'bold'))
b3 = Button(text='Italics',font=('z003',22,'italic'))
b4 = Button(text='Underline',font=('z003',22,'underline'))
b5 = Button(text='Strikethrough',font=('z003',22,'overstrike'))
b6 = Button(text='All',font=('z003',22,'bold','italic','underline','overstrike'))
FIGURE 1
Again, these can be combined to format your font the way you want it.
Justify
It may not be common, but if you have a button with multiple lines, they can be justified:
- Left
- Center
- Right
Code:
b1 = Button(text='Normal\nButton')
b2 = Button(text='Left\nButton',justify='left')
b3 = Button(text='Centered\nButton',justify='center')
b4 = Button(text='Right\nButton',justify='right')
FIGURE 2
You should notice that the longest line is set as the text width for all lines and the smaller lines are justified by the longest one.
Height and Width
Similar to the ‘height’ and ‘width’ of labels, we can control the height and width of a button. Keep in mind that the value given is in characters, not pixels.
So, let’s expand on what we’ve done so far. We can have code that will use two buttons. One button will change the height and the second will change the width of a third button. The third button has no function but to show the use of the height and width option.
Code:
from tkinter import *
def clicked(number):
global counth, countw
if number == "1":
counth += 1
elif number == "2":
countw += 1
b3["height"] = counth
b3["width"] = countw
root = Tk()
root.title('Button Height and Width')
root.geometry("400x800")
for row in range(0,9):
root.grid_rowconfigure(row, weight=1)
for col in range(0,3):
root.grid_columnconfigure(col, weight=1)
counth = 3
countw=15
b3 = Button(text="Change Me",bg='blue',height=counth,width=countw)
b1 = Button(text="Height",command=lambda: clicked("1"))
b2 = Button(text="Width",command=lambda: clicked("2"))
b1.grid(column=1, row=0)
b2.grid(column=1, row=2)
b3.grid(column=1, row=4)
root.mainloop()
Here, we have a button, named ‘b1’ that, when clicked, changes the height of button 3, named ‘b3’. The change is caused by a change in the global variable ‘counth’. Button 2, named ‘b2’, causes the variable named ‘countw’ to increment when pressed.
Notice too that both are calling the same function, but using an argument to specify which button is being pressed. After determining which button the user presses, it increments the variable. After this process, Button 3, named ‘b3’, is changed by the height and width or the new values of the variable, no matter which button the user clicks.
I’m hoping another example of ‘lambda’ helps show how to use it.
Anchor
We can anchor text to a specific area of the object. Similar to justify where you need multiple lines of text, in this case, you need multiple lines for the object. If the object only has a single line, the anchor does very little.
The anchor lets you specify a side of the button, or the center:
- NW - top left corner
- N - top center side
- NE - top right corner
- W - left side
- CENTER - middle of the object (default)
- E - right side
- SW - bottom left corner
- S - bottom center
- SE - bottom right corner
Code:
b1 = Button(text='NW', anchor="nw", height=3, width=25)
b2 = Button(text='N', anchor="n", height=3, width=25)
b3 = Button(text='NE', anchor="ne", height=3, width=25)
b4 = Button(text='W', anchor="w", height=3, width=25)
b5 = Button(text='Center', anchor="center", height=3, width=25)
b6 = Button(text='E', anchor="e", height=3, width=25)
b7 = Button(text='SW', anchor="sw", height=3, width=25)
b8 = Button(text='S', anchor="s", height=3, width=25)
b9 = Button(text='SE', anchor="se", height=3, width=25)
b1.grid(column=1, row=0)
b2.grid(column=2, row=0)
b3.grid(column=3, row=0)
b4.grid(column=1, row=1)
b5.grid(column=2, row=1)
b6.grid(column=3, row=1)
b7.grid(column=1, row=2)
b8.grid(column=2, row=2)
b9.grid(column=3, row=2)
FIGURE 3
Relief, OverRelief and BorderWidth
If you read the article on Labels, you may remember that the default border width for a Label is ‘0’. For a button, it is system specific and will either be ‘1’ or ‘2’. The Borderwidth is the amount of pixels around a button that are considered a ‘border’. The border can have a different color if needed.
The border is outside of the ‘relief’. The ‘relief’ is the style of ‘border’. Keep in mind that the ‘border’ you set actually outside of the ‘relief’. There are six different ‘reliefs’:
- flat
- raised
- sunken
- groove
- ridge
- solid
FIGURE 4
An example of setting the relief to ‘flat’ is:
Code:
b1 = Button(text="flat",relief="flat")
The option ‘overrelief’ is used to change the ‘relief’ of a button when the cursor hovers over the button. Do not confuse this with the ‘click’ event. This occurs when the cursor passes over or stops on a button. With any of the buttons, it will change color when the cursor hovers over it, but you can change the default.
The BorderWidth lets you override the default width of the border. The default is 1 or 2 depending on the Operating System. An example shows a normal button and one with a ‘borderwidth’ of 5 followed by the output in Figure 5:
Code:
b1 = Button(text='Normal')
b2 = Button(text='Width of 5',borderwidth=5)
FIGURE 5
Style
The style setup is used to apply for specific button widgets (W.TButton) or to all buttons (Tbutton).
‘Tbutton’ is the name used for buttons. The ‘style’ is a ‘ttk’ option and reauires ‘ttk’ to be imported:
Code:
from tkinter import *
from tkinter.ttk import *
Now that ‘ttk’ is imported into the code, we can use ‘style’.
After loading ‘ttk’, we must initialize the Style option:
Code:
styleinit1 = Style()
The ‘styleinit1’ variable can be any valid variable name. We then use the same variable name to configure the style:
Code:
styleinit1.configure('W.TButton',font=('z003', 25, 'bold'), foreground='blue')
We can use the name ‘W.Tbutton’ to specify which buttons will gain this style. You can change the ‘W’ if you want to set up multiple styles, such as ‘B1.Tbutton’, ‘B2.Tbutton’, etc.
To specify which button(s) to assign this style, we use the option ‘style=‘W.Tbutton’’ for the button:
Code:
btn1 = Button(text = 'Button 1',style = 'W.TButton')
If we want all buttons to be the same, or just the ones not given another style, we just specify ‘TButton’:
Code:
styleinit2 = Style()
styleinit2.configure(‘TButton',font=('z003', 25, 'bold'), foreground='green')
You can add as many options to the Style. Sometimes, you may set a specific style for all buttons, and when you add a button, all you need to specify is the text:
Code:
styleinit2 = Style()
styleinit2.configure(‘TButton',font=('z003', 25, 'bold'), foreground='green')
b1=Button(text=‘Button1’)
Even though we specify no style, it uses the default setup. This makes sure all buttons, with no style set, have the same appearance and you do not need to type all options for each button.
Underline
With this option, we can underline a letter on a button. This can help when setting up key bindings, so when the user presses special shortcut keys, it is as if the user clicks a button.
The default underlined character is ‘-1’ which is not one character in the text. The first character in the text is ‘0’ and so on.
An example is to underline the first letter for Button 1:
Code:
b1=Button(text="Button 1",underline=0,command=clicked)
Once we bind the ‘ALT+b’ keystroke, we can set it to run ‘clicked’ just as if the user presses it by the mouse.
I will not get into ‘Bindings’ in this article, but should be in the next article.
WrapLength
By default, a button will grow to contain all the text you specify. By setting the ‘wraplength’, in pixels, you can make sure all buttons have the same width.
Just specify the option ‘wraplength=’ and set the number of pixels. The following code has its output shown in Figure 6:
Code:
b1=Button(text="Button 1 - Default")
b2=Button(text="Button 2 - WrapLength 50",wraplength=50)
b3=Button(text="Button 3 - WrapLength 100",wraplength=100)
b1.grid(column=1, row=0)
b2.grid(column=1, row=1)
b3.grid(column=1, row=2)
FIGURE 6
You can see that the second button cuts off words to continue it on the next line. You may need to play with the numbers to get a button to look right.
Padding
Padding allows us to add space around the text in a button.
We can pad the area to the left and right of the text with the option ‘padx’, or above and below the text with ‘pady’. You can also pad both ‘padx’ and ‘pady’ together as well. The value given to the option is based in pixels.
Let’s look at an example with the output in Figure 7:
Code:
b1=Button(text="Button 1 - Default")
b2=Button(text="Button 2 - PadX",padx=10)
b3=Button(text="Button 3 - PadY",pady=10)
b4=Button(text="Button 4 - PadXY",padx=10,pady=10)
FIGURE 7
TakeFocus
If there are multiple widgets in the window, we can use the TAB key to switch between the objects. An object that is currently ‘selected’ by the TAB key has focus. For a widget to be on the list that can be selected by the TAB key, it must be allowed to ‘takefocus’. Most objects will ‘takefocus’ by default, the buttons are a good example. Any widget that can interact with the user usually ‘takefocus’. If you look back at labels, these do not ‘takefocus’ by default.
You can disable the ability by a button to ‘takefocus’ by:
Code:
takefocus=NO
If you want an object, such as a button named ‘b1’, to ‘takefocus’ you can:
Code:
b1=Button(text=”Button 1”,takefocus=YES)
If a button has focus, then it will be surrounded by a black line, as in Figure 8.
FIGURE 8
Here, see that ‘Button 1’ has focus.
When a button has focus, it has a black highlight that you can change.
HighlightColor, HighlightBackground and HighlightThickness
If a button has the focus, the default ‘highlightcolor’ is black.
When a button does not have focus, you can set the ‘highlightbackground’.
The highlighted box has a specific thickness of 1 or 2 depending on the Operating System. You can change the background thickness with the option ‘highlightthickness’.
Let’s have an example. I’ll make six buttons. The even buttons will have a ‘highlightbackground’ of ‘red’ and the odd ones will be ‘blue’. The ‘highlightcolor’ will be purple. Buttons 5 and 6 will have a thickness of 4 while the rest are the default.
The code is followed by the output in Figure 9:
Code:
b1=Button(text="Button 1",highlightbackground='blue',highlightcolor='purple')
b2=Button(text="Button 2",highlightbackground='red',highlightcolor='purple')
b3=Button(text="Button 3",highlightbackground='blue',highlightcolor='purple')
b4=Button(text="Button 4",highlightbackground='red',highlightcolor='purple')
b5=Button(text="Button 5",highlightbackground='blue',highlightcolor='purple',highlightthickness=4)
b6=Button(text="Button 6",highlightbackground='red',highlightcolor='purple',highlightthickness=4)
FIGURE 9
ActiveForeground, ActiveBackground and DisabledForeground
An object has three states. Those states are:
- normal - the default
- active - the button will be highlighted as shown in Figure 10
- disabled - the button will be grayed out and will not be allowed to take focus
Code:
b1=Button(text="Normal",state='normal')
b2=Button(text="Active 1",state='active')
b3=Button(text="Active 2",state='active')
b4=Button(text="Disabled",state='disabled')
FIGURE 10
These are the default colors for the state being ‘active’ or ‘disabled’. You can set your own with the options:
- activeforeground - the text color of a button that is ‘active’
- activebackground - the background color of a button that is active
Cursor
If you should move the cursor over a button, you can change the cursor that is seen by a user. You can look at the article for Labels (Python 17 - Labels) to see the list. Use one of these cursor types for a button. The cursor reverts when it is no longer over the button.
An example is to make the cursor an ‘X’ when it moves over the button:
Code:
b1=Button(text="Button 1",cursor='X_cursor')
Image
Instead of having text in a button, we can place an image in it. There are two types of options:
- bitmapimage - monochrome image
- photoimage - color image (PNG)
First, you need to load the image and then use the loaded image as a button:
Code:
image1=PhotoImage(file="/home/jarret/Python/tux1.png")
b1=Button(image=image1,cursor='X_cursor')
Remember that the path to the image is case-sensitive. Also, if you have a large image, the button will resize to match the image size.
You can omit the path to the image file if the image is in the same folder as the python code.
Compound
If we wanted, we can put text and an image in a button. By using both, this is a ‘compound’.
There are five different parameters for ‘compound’:
- TOP
- BOTTOM
- LEFT
- RIGHT
- BOTTOM
Example code is:
Code:
image1=PhotoImage(file="/home/jarret/Python/tux1.png")
b1=Button(text="Top",image=image1,compound=TOP)
b2=Button(text="Bottom",image=image1,compound=BOTTOM)
b3=Button(text="Left",image=image1,compound=LEFT)
b4=Button(text="Right",image=image1,compound=RIGHT)
b5=Button(text="Center",image=image1,compound=CENTER)
The output is shown in Figure 11.
FIGURE 11
Bitmap
We can use built-in bitmap images for the buttons. There are ten different images:
- error
- gray75
- gray50
- gray25
- gray12
- info
- questhead
- question
- hourglass
- warning
Code:
b1=Button(bitmap='error')
b2=Button(bitmap='gray12')
b3=Button(bitmap='gray25')
b4=Button(bitmap='gray50')
b5=Button(bitmap='gray75')
b6=Button(bitmap='info')
b7=Button(bitmap='questhead')
b8=Button(bitmap='question')
b9=Button(bitmap='hourglass')
b10=Button(bitmap='warning')
FIGURE 12
In the output, I added labels for each line. Any ‘text’ you specify for the button is ignored. It is possible to use ‘foreground’ and ‘background’ colors, so it is not plain gray.
You can use your own BMP files, but you need to convert them to XBM files, which are monochrome. Sample code is:
Code:
image1=BitmapImage(file='tux1.xbm')
b1=Button(image=image1)
Here, the ‘tux1.xbm’ file is in the same folder as the Python file.
Invoke
When using the ‘invoke’ command, we can cause a button’s command function to be called without the user actually clicking on the button.
Say, for example, we have a button named ‘b1’. We can programmatically cause it to be pressed by using the command ‘b1.invoke()’ and the function listed with the ‘command’ option will be executed.
Flash
Using the ‘flash’ option will cause the button to be redrawn as it alternates between a ‘normal’ and ‘active’ state.
You can specify ‘active colors to change the flashing colors. When it is done flashing, it goes back to a ‘normal’ state.
An example of the command is:
Code:
b1.flash()
Conclusion
Hopefully, this gets you working well with buttons in tkinter in Python.
Having Buttons will give you the possibility of more interaction with your programs.

