Python彩色文本循环切换报错:'str'对象不可调用问题求助
Hey Jake, let's break down why your script stops after one cycle and throws that error!
The core issue is a name collision inside your hello() function: you've used the same name hello for both your function and a string variable (hello = '''Hello!'''). When you do this, you overwrite the original reference to the hello() function. By the time you reach the final hello() call to restart the cycle, Python sees hello as a string instead of a function—hence the TypeError: 'str' object is not callable.
Quick Fixes & Improvements:
- Rename the string variable: Pick a different name like
greetingormessageto avoid clashing with the function name. - Initialize colorama once: You don't need to run
init()every time the function loops—move it to the top of your script since it only needs to run once. - Clean up the loop: Instead of repeating the same print/sleep code three times, use a list of colors and iterate over it for cleaner, more maintainable code.
Revised Working Code (Infinite Cycle):
import time, sys, os from colorama import init from termcolor import colored # Initialize colorama once at startup init() def hello(): greeting = '''Hello!''' # List of colors to cycle through color_list = ['green', 'blue', 'yellow'] for color in color_list: os.system('cls') print(colored(greeting, color)) time.sleep(1) # Restart the cycle by calling the function again hello() hello()
Bonus: Add an Exit Option
For a more user-friendly version, use a while True loop (instead of recursion, which can hit Python's recursion limit after many cycles) and handle Ctrl+C to let the user exit cleanly:
import time, sys, os from colorama import init from termcolor import colored init() def hello(): greeting = '''Hello!''' color_list = ['green', 'blue', 'yellow'] while True: for color in color_list: os.system('cls') print(colored(greeting, color)) time.sleep(1) try: hello() except KeyboardInterrupt: print("\nExiting the color cycle!") sys.exit(0)
内容的提问来源于stack exchange,提问作者Jake

