【问题标题】:python: how to easily display blinking filled circlepython:如何轻松显示闪烁的实心圆圈
【发布时间】:2020-04-17 15:09:07
【问题描述】:

我是 python 新手。如果我的 vpn 隧道关闭,我试图获得一个闪烁的红色圆圈(指示器),如果我的 vpn 启动,我将获得稳定的绿色。但是,我目前陷入困境的是建立这个闪烁的红灯。

我试过了:

#!/usr/bin/env python
import turtle

turtle.setup(100,150)

t = turtle.Turtle()
t.speed(0)
while True:
    #Python program to draw color filled circle in turtle programming
    t.begin_fill()
    t.fillcolor('red')
    t.circle(25)
    t.end_fill()
    t.begin_fill()
    t.fillcolor('white')
    t.circle(25)
    t.end_fill()
turtle.done()

它几乎就在那里,只是绘制圆圈需要“很长时间”。还有其他更好的方法吗?顺便说一句,是否可以获得透明背景?

【问题讨论】:

    标签: python tkinter pygame python-turtle


    【解决方案1】:

    你可以摆弄turtle.speed 命令。

    设置t.speed(0) 会导致快速闪烁。

    【讨论】:

    • 抱歉,我编辑了答案:应该是t.speed(0)
    • 对不起,我的错误。它有效。谢谢! Uodated with the correction.但它确实会在一段时间后变慢,这没关系,除非它会变慢并占用更多资源。
    • 对不起,但是越来越慢了。
    • 哦。我不确定为什么会这样,这可能与海龟如何管理填充有关(这不是一项简单的任务,您必须计算海龟路径所包围的区域)。在这种情况下,您可能需要考虑另一个绘图库,它拥有直接的圆形绘图图元(turtle 似乎不适合您的用例)。你知道pygame吗?
    【解决方案2】:

    让我们尝试一种不同的方法,使用ontimer() 事件来控制闪烁速度并让圆形海龟闪烁,而不是每次都重绘:

    from turtle import Screen, Turtle
    
    CURSOR_SIZE = 20
    
    def blink():
        pen, fill = turtle.color()
        turtle.color(fill, pen)
        screen.ontimer(blink, 250)  # 1/4 second blink
    
    screen = Screen()
    
    turtle = Turtle()
    turtle.hideturtle()
    turtle.shape('circle')
    turtle.shapesize(50 / CURSOR_SIZE)
    turtle.color('red', 'white')
    turtle.showturtle()
    
    blink()
    
    screen.exitonclick()
    

    【讨论】:

    • 谢谢,那么,哪个更好?乌龟还是 pygame?它似乎最终放缓了一点。我想我应该运行几天才能看到。
    • @user3236841,两者都不是更好,它们只是具有不同目标的不同环境。您的特定问题属于它们的重叠部分。我很惊讶它仍然会减慢速度,但如果您需要更精确的闪烁时间,您可以考虑将级别降低到 tkinter,即乌龟所在的顶部。
    • 你能给我一个关于如何使用 tkinter 做到这一点的参考吗?谢谢!
    【解决方案3】:

    Pygame 做到了:

    #!/usr/bin/env python
    
    import pygame
    import time
    
    WHITE =     (255, 255, 255)
    RED =       (255,   0,   0)
    (width, height) = (40, 40)
    
    background_color = WHITE
    
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption("VPN-Status")
    screen.fill(background_color)
    pygame.display.update()
    
    while True:
        pygame.draw.circle(screen, RED, (20, 20), 20)
        pygame.display.update()
        time.sleep(0.25)
        pygame.draw.circle(screen, WHITE, (20, 20), 20)
        pygame.display.update()
        time.sleep(0.25)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-30
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-21
      • 1970-01-01
      • 2018-06-17
      相关资源
      最近更新 更多