【问题标题】:drawing a point on the screen every 17ms in Python?在 Python 中每 17 毫秒在屏幕上绘制一个点?
【发布时间】:2014-03-01 14:19:36
【问题描述】:

我设法将一个脚本串在一起,该脚本接收来自 iOS 应用程序设置速度和方向的命令。

问题是我没有实际的设备,所以我的应用程序将命令发送到我构建的使用龙卷风的小型 python web 套接字服务器......

基本上我理想中需要的是一种方法:

显示一个窗口 每隔 17ms,清空窗口,用 x 和 y 读取一个全局变量,并在 x 和 y 处画一个点或圆。

有没有一种方便的方法可以让我直观地看到发生了什么?

如果我能每 X 毫秒在窗口中画一个圆圈,我就可以处理剩下的事情。

需要补充的:

-create a window
-create a timer
on timer callback: clear screen and draw a circle in the window.

【问题讨论】:

  • 你能发布你的脚本吗?没有样本来讨论你的代码是很困难的。您希望窗口显示在哪里?在设备上?你能详细列举一下步骤吗?
  • @MylesBaker python 脚本在我的电脑上运行,我需要脚本在我的电脑上显示一个圆圈,我在终端窗口中运行脚本。理想情况下,我想制作一个窗口并在其中绘制。
  • 您需要选择一个库进行绘图。见这里:stackoverflow.com/questions/326300/…

标签: python


【解决方案1】:

您可以将终端用作“窗口”并在其中画一个“圆圈”。作为一个非常简单(且不可靠)的“定时器”,可以使用time.sleep() 函数:

#!/usr/bin/env python
"""Print red circle walking randomly in the terminal."""
import random
import time
from blessings import Terminal # $ pip install blessings colorama
import colorama; colorama.init() # for Windows support (not tested)

directions = [(-1, -1), (-1, 0), (-1, 1),
              ( 0, -1),          ( 0, 1),
              ( 1, -1), ( 1, 0), ( 1, 1)]
t = Terminal()
with t.fullscreen(), t.hidden_cursor():
    cur_y, cur_x = t.height // 2, t.width // 2 # center of the screen
    nsteps = min(cur_y, cur_x)**2 # average distance for random walker: sqrt(N)
    for _ in range(nsteps):
        y, x = random.choice(directions)
        cur_y += y; cur_x += x # update current coordinates
        print(t.move(cur_y, cur_x) +
              t.bold_red(u'\N{BLACK CIRCLE}')) # draw circle
        time.sleep(6 * 0.017) # it may sleep both less and more time
        print(t.clear) # clear screen

要试一试,请将代码保存到 random-walker.py 并运行它:

$ python random-walker.py

我不知道它是否适用于 Windows。

【讨论】:

    【解决方案2】:

    您应该尝试使用 pygame 进行图形工作。 先下载pygame

    这是一个示例代码

    import pygame,sys
    from pygame import *
    
    WIDTH = 480
    HEIGHT = 480
    WHITE = (255,255,255) #RGB
    BLACK = (0,0,0) #RGB
    
    pygame.init()
    screen = display.set_mode((WIDTH,HEIGHT),0,32)
    display.set_caption("Name of Application")
    screen.fill(WHITE)
    timer = pygame.time.Clock()
    pos_on_screen, radius = (50, 50), 20    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        timer.tick(60) #60 times per second you can do the math for 17 ms
        draw.circle(screen, BLACK, pos_on_screen, radius)
        display.update()
    

    希望能有所帮助。请记住,您需要先下载 pygame。 您还应该阅读 pygame。真的很有帮助。

    【讨论】:

    • 碰巧,17ms 几乎是 60 fps。
    • 完成。现在应该已经完成​​了。
    【解决方案3】:
    猜你喜欢
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多