Change Text in Button dynamically - Tkinter


Python Tkinter - Change Button Text Dynamically

You can change the text property of Tkinter button using the reference to the button and 'text' option as index.

To set the button's text property, assign a new value as shown below:

button['text'] = 'new value'

To read the button's text property to a variable, use code as shown below:

bText = button['text']

Now bText contains the text of the button.

Examples

1. Change text of Tkinter button from "Submit" to "Submitted"

In this example, we pack a button to the window and set a command function. And in the command function, we are assigning a new value to the button's text property.

When you click on the button, the text is changed dynamically.

Python Program

from tkinter import *

tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('PythonExamples.org - Tkinter Example')

def changeText():  
    button['text'] = 'Submitted'

button = Button(tkWindow,
	text = 'Submit',
	command = changeText)  
button.pack()  
  
tkWindow.mainloop()

Output

2. Change button text based on button's text

In this example, we will change the Button Text, based on the existing text value of button.

Python Program

from tkinter import *

tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('PythonExamples.org - Tkinter Example')

def toggleText():  
	if(button['text']=='Submit'):
		button['text']='Submitted'
	else:
		button['text']='Submit'

button = Button(tkWindow,
	text = 'Submit',
	command = toggleText)  
button.pack()  
  
tkWindow.mainloop()

Output

Summary

Summarizing this tutorial of Python Examples, we learned how to change the text/label of Button dynamically during runtime.