Python使用Pygame繪製時鐘

2022-09-26 01:06:12 字數 2539 閱讀 6692

前提條件:

需要安裝pygame

功能:1.初始化介面顯示乙個時鐘介面

2.根據當前的時間實現時針、分針、秒針的移動

import pygame, sys, random, math

from datetime import datetime

from pygame.locals import *

def print_text(font, x, y, text, color=(255, 255, 255)):

img_text = font.render(text, true, color)

screen.blit(img_text, (x, y))

pygame.init()

# 螢幕大小

screen = pygame.display.set_mode((600, 500))

# 標題

pygame.display.set_caption("時鐘")

# 字型

font1 = pygame.font.font(none, 24)

# 圓心位置

pos_x = 300

pos_y = 250

# 圓的半徑

radius = 250

r = random.randint(0, 255)

g = random.randint(0, 255)

b = random.randint(0, 255)

while true:

for event in pygame.event.get():

if event.type == quit:

sys.exit()

keys = pygame.key.get_pressed()

if keys[k_escape]:

sys.exit()

screen.fill((0, 0, 100))

color = r, g, b

pygame.draw.circle(screen, color, (pos_x, pos_y), radius, 6)

# 繪製數字1-12

for i in range(1, 13):

angle = math.radians((360 / 12) * i - 90)

x = math.cos(angle) * (radius - 20) - 10

y = math.sin(angle) * (radius - 20) - 10

print_text(font1, pos_x + x, pos_y + y, str(i))

# 繪製時針

hour = datetime.today().hour % 12 # 獲取當前時間的小時

hour_angle = math.radians((360 / 12) * hour - 90)

hour_x = math.cos(hour_angle) * (radius - 90)

hour_y = math.sin(hour_angle) * (radius - 90)

pygame.draw.line(screen, (255, 0, 0), (pos_x, pos_y), (pos_x + hour_x, pos_y + hour_y), 12)

# 繪製分針

minutes = datetime.today().minute # 獲取當前時間的分鐘

minutes_angle = math.radians((360 / 60) * minutes - 90)

minutes_x = math.cos(minutes_angle) * (radius - 70)

minutes_y = math.sin(minutes_angle) * (radius - 70)

pygame.draw.line(scree程式設計客棧n, (0, 255, 0), (pos_x, pos_y), (pos_x + minutes_x, pos_y + minutes_y), 8)

# 繪製秒針

seconds = datetime.today().second # 獲取當前時間的秒數

second程式設計客棧s_angle = math.radians((360 / 60) * seconds - 90)

seconds_x = math.cos(seconds_angle) * (radius - 30)

seconds_y = math.sin(seconds_angle) * (radius - 30)

pygame.draw.line(screen, (0, 0, 255), (pos_x, pos_y), (pos_x + seconds_x, + pos_y + seconds_y), 4)

# 覆蓋圓心

pygame.draw.circle(screen, (255, 255, 255), (pos_x, pos_y), 10)

pygame.display.update()

執行結果:

本文標題: python使用pygame繪製時鐘

本文位址: /jiaoben/python/366698.html

python 使用 vtkPolyData 繪線

vtk 可以通過vtkpolydata 繪製曲線以及三角麵片,下面的 簡單的繪製乙個線。使用到如下 vtk的類 如下 import vtk import numpy as np class ployline vtk.vtkobject 繪製中心線 def init self 構造2d的線 self....

python使用pygame建立精靈Sprite

精靈組可以對其中的所有精靈呼叫它們各自的更新方法 s程式設計客棧elf.update 來進行更新,如位置更新 碰撞檢測 衝突檢測等 all sprites.update 精靈組可以對其中的所有精靈呼叫它們各自的draw方法 self.update 來繪製精靈 all sprites.draw scr...

使用Python和pyGame進行虛擬儀器開發

說明 這是我2007年寫在cublog china unix 上的部落格,現在把它轉到這裡來.偶然發現pygame的高速繪圖效果,於是忽然想做乙個虛擬示波器,以前經常見到基於 visual c 的收費的類庫,感覺太複雜了,根本沒想過要自己寫乙個.然而使用python後,一切都變得很簡單了.當然,目前...