Python 3 print text using 24bit (HTML5) rgb code

不问归期 提交于 2020-01-16 00:43:07

问题


In my script I wish to input rgb(red,green,blue) color code 24bit (HTML5) as background color and as text color. But I can't get it to work. The resulting color code is different from what I copied from the w3schools Color Picker.

See my Repl.it code example or code bellow:

from sty import fg, bg, ef, rs, Rule
import time
import sys

def isInteger(n): #function from the internet that checks if a float is a int
    if n%2 == 0 or (n+1)%2 == 0:
        return True
    return False

def make_int(value):
  try:
    int(value)
    return value
  except:
    return 0

# Function to ask rgb color code : “(#red, #green, #blue)” where #red, #green and #blue should be 0-255
# return this as list variable : color_code = [ #red, #green, #blue ] 

def input_color(question):
  ValidInput = False
  while not ValidInput:
    color = input(question)
    if ( len(color) < 5 ) or ( color.count(",") != 2 ):
      ValidInput = False
    else:
      color_code = color.replace("(", "").replace(")", "").replace("rgb","").split(",")
      IsOK = input("OK? (y/n)")
      ValidInput = ( len(IsOK)==0 or IsOK=="y" )
  return color_code

from termcolor import colored, cprint

# Initial first Elements

elements = ['fire', '\x1b[48;2;204;41;0m\x1b[38;2;255;153;0m\x1b[1mfire\x1b[39m', 'water', '\x1b[48;2;51;204;255m\x1b[38;2;51;51;255m\x1b[1mwater\x1b[39m', 'earth', '\x1b[48;2;153;77;0m\x1b[38;2;77;38;0m\x1b[1mearth\x1b[39m', 'air', '\x1b[48;2;51;204;255m\x1b[38;2;255;255;255m\x1b[1mair\x1b[39m']

# Loop forever : 1. print elements-list, 2. Ask for new element with text color combination

while True:

# 1. print elements-list
  for i in range( int(len(elements) / 2)):
    print("")
    print(elements[i * 2 + 1])
  print("")

# 2. Ask for new element with text color combination
# Ask for a new element and check if name is already used
# if not then ask for text-background (color_b) and text color (color_t) and store the combination in the elements-list 
  name = input(bg.black + fg.white + ef.bold + 'new elements name:' + fg.rs)
  if name in elements:
    print(bg.black + fg.white + ef.bold + 'name already used' + fg.rs)

  else:
    color_b = input_color(bg.black + fg.white + ef.bold + 'rgb for the background:' + fg.rs)
    color_t = input_color(bg.black + fg.white + ef.bold + 'rgb for the text:' + fg.rs)

    elements.append(name)
    elements.append(bg(color_b[0], color_b[1], color_b[2] ) + fg(color_t[0], color_t[1], color_t[2]) + ef.bold + name + fg.rs)

来源:https://stackoverflow.com/questions/53818849/python-3-print-text-using-24bit-html5-rgb-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!