Skip to main content
 首页 » 编程设计

python之如何让闪烁的字符串也改变值 ( python 3.5)

2025年05月04日23飞鱼

我在 Python 3.5 中有以下代码:

def blink(char):                        
    while 1:                                
        print (char, end = '\r')            
        time.sleep(0.5)                        
        print (' ' * 50, end = '\r')        
        time.sleep(0.5)         

I am using this function to make any string blink for a specific time

问题是,当我在下面的代码中使用它时,它没有达到预期的效果:

while True: 
    time.sleep(0.5) 
    seconds += 1 
    if seconds == 60: 
        minutes += 1 
        seconds = 0 
    if minutes == 60: 
        hours += 1 
        minutes = 0 
    if hours == 24: 
        days += 1 
        hours = 0 
    blink ('Days: %s, Hours: %s, Minutes: %s, Seconds: %s' % (days, hours, minutes, seconds)) 

I'm using this piece of code to 'simulate' time. The problem is that the output looks like this:

Days: 0, Hours: 0, Minutes: 0, Seconds: 1 

This keeps on blinking on the same line as I want it to, but the problem is that the output doesn't increase.

e.g Days: 0, Hours: 0, Minutes: 0, Seconds: 2 etc.  

请您参考如下方法:

blink(char) 函数没有结束,所以 while True 循环将卡在它的第一个循环中。

尝试从闪烁函数中移除 while 循环,使其只闪烁一次:

def blink(char):                        
    print(char, end = '\r')            
    time.sleep(0.5)                        
    print(' ' * 50, end = '\r')        
    time.sleep(0.5) 

(或者创建一个单独的 blink_once 函数。)