Tkinter

How to Change Text of Button When Clicked in Tkinter Python

In this tutorial, we are going to see how to change the text of a button when clicked in Tkinter Python. You can change the “text” property of the Tkinter button by using the button reference and the “text” option as an index.

To set the “text” property of the button, assign a new value as shown below:

button['text'] = 'new value'

To read the “text” property of a button in a variable, use the code as shown below:

value = button['text']

Now ‘value’ contains the button text.
 

 

Example 1: Change the text of a button by clicking on it

In the following example, we add a button in the window and define a function associated with the command option. And in the function, we assign a new value to the “text” property of the button.

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

from tkinter import *

gui = Tk()  
gui.geometry('200x100')  

def changeText():  
    btn['text'] = 'Ipsum'

btn = Button(gui, text='Lorem', command=changeText)  
btn.pack()  
  
gui.mainloop()

Output:


 
 

Example 2: Change the text button based on the existing text

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

from tkinter import *

gui = Tk()  
gui.geometry('200x100')  

def changeText():  
	if(btn['text']=='Lorem'):
		btn['text']='Ipsum'
	else:
		btn['text']='Lorem'

btn = Button(gui, text='Lorem', command=changeText)  
btn.pack()  
  
gui.mainloop()

Output:


 
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *