Python Forum
colored input() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: colored input() (/thread-13387.html)



colored input() - Trianne - Oct-12-2018

Hello,

How would I colored input prompt? I know how to when printing but not input.

I got this so far.

from colorama import init
from termcolor import colored

init()

def computer_prompt():
    return (colored('Computer: ', 'green', 'on_blue'))
def user_prompt():
    return (colored('User: ', 'yellow', 'on_blue'))

print(computer_prompt()+'Please enter a word.')

word = input(user_prompt()+('?: '))

print(word)
You can see that 'Computer: ' returns with green text but how do I color the 'User: ' input?

I get the following error when running this code:

Error:
<-[44m<-[33m?: <-[0m?:
I thought it was as easy as creating a function like computer_prompt but I just couldn't get the result I was looking for.

Please help.

Thank You.


RE: colored input() - wavic - Oct-13-2018

İmage


You can write a wrapper function for all input and output colors.
Something like this

from colorama import init
from colorama import Fore as F
from colorama import Back as B
from colorama import Style

def color(fore='', back='', text):
    return f'{fore}{back}{text}{Style.RESET_ALL}'

print(color(F.GREE, B.BLUE, 'Hello there!'))
You may also want to look at prompt_toolkit It's a powerful library which can do a lot more instead of just colored terminal.


RE: colored input() - Trianne - Oct-15-2018

Hello Wavic,

When I ran this code..
from colorama import init, Fore, Back, Style
init()
word = input(Fore.YELLOW + Back.BLUE + '?: ' + Style.RESET_ALL)
I get the follow error
Error:
<-[33m<-[44m?: <-[0m
I am not sure what it means.

Please help.


RE: colored input() - wavic - Oct-15-2018

Post the full error traceback please.

I think it's something with your terminal.



Also, I see that there is an error in my function definition example. The arguments are in a wrong order.

Read this: https://en.wikipedia.org/wiki/ANSI_escape_code


RE: colored input() - nilamo - Oct-15-2018

input() might be escaping the color codes. Try just printing it out:
print(Fore.YELLOW + Back.BLUE + '?: ' + Style.RESET_ALL, end="")
word = input()



RE: colored input() - Trianne - Oct-15-2018

Nilamno,

That works perfectly.

Thank you Nilamo and Wavic for your help.

Trianne


RE: colored input() - wavic - Oct-15-2018

Hm! Why is that behavior of the input? May be you can see that I get the expected.