欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python使用Pygame绘制时钟

时间:2021-12-09 18:07:25|栏目:Python代码|点击:

本文实例为大家分享了Python使用Pygame绘制时钟的具体代码,供大家参考,具体内容如下

前提条件:

需要安装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(screen, (0, 255, 0), (pos_x, pos_y), (pos_x + minutes_x, pos_y + minutes_y), 8)
 # 绘制秒针
 seconds = datetime.today().second # 获取当前时间的秒数
 seconds_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()

运行结果:

上一篇:Python3中条件控制、循环与函数的简易教程

栏    目:Python代码

下一篇:python处理圆角图片、圆形图片的例子

本文标题:Python使用Pygame绘制时钟

本文地址:http://www.codeinn.net/misctech/186341.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有