python--在线签名生成(控制台和GUI)

今天给大家简单分享一下基于python语言编写的一个在线生成签名的小代码

代码中所涉及用到的知识:

爬虫领域的requests模块,以及pygame模块,easygui模块,和一些python基础。

实现的功能:

可以自定义输入你要生成的签名的字体类型和内容,当输入不合法的内容时给予提示(弹出一个esaygui的msgbox框),然后信息输入完成后会在线联网生成你输入设置的签名的字体类型和内容的照片,并保存再你当前项目的同一目录下。

开发过程:

控制台版本的我就不在此多言了,很简单的,我下面就简单说一下基于pygame图形界面开发的版本吧,主要就是大概说一下这个项目的主要一个流程和关键代码,当然现在以及凌晨一点了,我可能写的不会太细太全面,还请大家包含一下咯。

项目运行效果的输入框时用Inputbox对象写的,输入时用pygame的

pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:

来实现鼠标点击输入框

event.type == pygame.KEYDOWN:

来实现获取键盘事件

elif(event.key == pygame.K_BACKSPACE):
    self.text = self.text[:-1]

实现当按下spaceback键删除当前输入的末尾字符,但是有一个不解的时,我单独写这个输入框的功能时,按下backspace键就可以进行删除,但是写在这个项目里就不行,比如我签名内容为xbtt,此时我想按下backspace键删除一个t,我在控制台输出打印显示就是xbt,但是呢就是界面显示不出来,还是显示xbtt,有问题不能直接解决就间接解决,我在按下backspace键的时候添加了如下四行代码:

rect2 = pygame.Rect(488, 97, 192, 26)
color = (52, 78, 91)
pygame.draw.rect(screen, color, rect2)
pygame.display.flip()

没错就是按下键时我把输入框的背景先填充成背景颜色,然后再刷新屏幕,发现问题就解决了,内容就可以随时动态变化了。

另外就是自己添加的一些简单的互动性的东西了,如进入主界面需要先按空格键来判断是否人为操作,以及一些提示,和退出程序的按钮等等

总代码:

控制台版:

import requests
from bs4 import BeautifulSoup
print("*"*15+"欢迎来到在线生成签名平台"+"*"*15)
print("1:艺术签 2:连笔签 3:商务签 4:楷书签 5:潇洒签 6:草体签 7:行书签 8:个性签 9:可爱签")
headers ={
          "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36"}
url = "http://www.uustv.com/"
run=True
while run:
    a = input("请输入你要生成的签名类型序号:")
    if a=="back":
        print("程序已退出,欢迎下次使用!!!")
        break
    name = input("你要生成签名的内容:")

    if int(a) > 0 and int(a) < 4:
        a = int(a)
    elif int(a) > 3 and int(a) < 7:
        a = int(a) - 3
    elif int(a) == 7 or int(a) == 8 or int(a)==9:
        a = int(8)
    else:
        print("你输入的字体类型暂不存在有误,请重新输入")
        a = input("请输入你要生成的签名类型序号:")
        name = input("你要生成签名的内容:")
    from_data = {
              "word": name,
              "sizes": "60",
              "fonts": str(a)+".ttf"
          }
    res = requests.post(url, data=from_data, headers=headers)
    text1 = res.content.decode()
    soup = BeautifulSoup(text1, "lxml")
    img_list = soup.find_all('img')
    url_img = img_list[0].get('src')
    img_message = requests.get("http://www.uustv.com/" + url_img, headers=headers)
    print("签名网页地址为:http://www.uustv.com/"+url_img)
    with open(name+".png", "wb") as file:
        file.write(img_message.content)
    print("签名已生成完毕!!!")

pygame(GUI)版:

button_new.py

import pygame

#按钮类
class Button():
	def __init__(self, x, y, image, scale):
		width = image.get_width()
		height = image.get_height()
		self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
		self.rect = self.image.get_rect()
		self.rect.topleft = (x, y)
		self.clicked = False

	def draw(self, surface):
		action = False
		pygame.draw.rect(surface, (0, 0, 0), (self.rect.x, self.rect.y, self.image.get_width(), self.image.get_height()))
		bk = pygame.draw.rect(surface, (255, 255, 255), (self.rect.x, self.rect.y, self.image.get_width(), self.image.get_height()), 3)
		#得到鼠标的位置
		pos = pygame.mouse.get_pos()

		#判断鼠标划过按钮并点击
		if bk.collidepoint(pos):
			if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
				self.clicked = True
				action = True
				pygame.draw.rect(surface, (0, 0, 255),
								 (self.rect.x, self.rect.y, self.image.get_width(), self.image.get_height()))

		if pygame.mouse.get_pressed()[0] == 0:
			self.clicked = False

		#画按钮到屏幕
		surface.blit(self.image, (self.rect.x, self.rect.y))

		return action

main_new.py

import button_new
import easygui
import sys
import requests
import pygame
from easygui import msgbox
from pygame import Surface
from pygame.constants import QUIT
from bs4 import BeautifulSoup
pygame.init()
import os
class InputBox:
    a=""
    def __init__(self, rect: pygame.Rect = pygame.Rect(100, 100, 100, 32)) -> None:
        """
        rect,传入矩形实体,传达输入框的位置和大小
        """
        self.boxBody: pygame.Rect = rect
        self.color_inactive = pygame.Color('lightskyblue3')  # 未被选中的颜色
        self.color_active = pygame.Color('dodgerblue2')  # 被选中的颜色
        self.color = self.color_inactive  # 当前颜色,初始为未激活颜色
        self.active = False
        self.text = ''
        self.done = False
        self.font = pygame.font.Font(None, 32)

    def dealEvent(self, event: pygame.event.Event):
        if(event.type == pygame.MOUSEBUTTONDOWN):
            if(self.boxBody.collidepoint(event.pos)):  # 若按下鼠标且位置在文本框
                self.active = not self.active
            else:
                self.active = False
            self.color = self.color_active if(
                self.active) else self.color_inactive
        if(event.type == pygame.KEYDOWN):  # 键盘输入响应
            if(self.active):
                if(event.key == pygame.K_RETURN):
                    print(self.text)
                elif(event.key == pygame.K_BACKSPACE):
                    self.text = self.text[:-1]
                    rect1 = pygame.Rect(156, 94, 144, 28)
                    color = (52, 78, 91)
                    pygame.draw.rect(screen, color, rect1)
                else:
                    self.text += event.unicode
                    global a
                    a=self.text
    def draw(self, screen: pygame.surface.Surface):
        txtSurface = self.font.render(
            self.text, True, self.color)  # 文字转换为图片
        width = max(200, txtSurface.get_width()+10)  # 当文字过长时,延长文本框
        self.boxBody.w = width
        screen.blit(txtSurface, (self.boxBody.x+5, self.boxBody.y+5))
        pygame.draw.rect(screen, self.color, self.boxBody, 2)

class InputBox1:
    name=""
    def __init__(self, rect: pygame.Rect = pygame.Rect(100, 100, 100, 32)) -> None:
        """
        rect,传入矩形实体,传达输入框的位置和大小
        """
        self.boxBody: pygame.Rect = rect
        self.color_inactive = pygame.Color('lightskyblue3')  # 未被选中的颜色
        self.color_active = pygame.Color('dodgerblue2')  # 被选中的颜色
        self.color = self.color_inactive  # 当前颜色,初始为未激活颜色
        self.active = False
        self.text = ''
        self.done = False
        self.font = pygame.font.Font(None, 32)
    def dealEvent(self, event: pygame.event.Event):
        if(event.type == pygame.MOUSEBUTTONDOWN):
            if(self.boxBody.collidepoint(event.pos)):  # 若按下鼠标且位置在文本框
                self.active = not self.active
            else:
                self.active = False
            self.color = self.color_active if(
                self.active) else self.color_inactive
        if(event.type == pygame.KEYDOWN):  # 键盘输入响应
            if(self.active):
                if(event.key == pygame.K_RETURN):
                    print(self.text)
                elif(event.key == pygame.K_BACKSPACE):
                    self.text = self.text[:-1]
                    rect2 = pygame.Rect(488, 97, 192, 26)
                    color = (52, 78, 91)
                    pygame.draw.rect(screen, color, rect2)
                    pygame.display.flip()
                else:
                    self.text += event.unicode
                    global name
                    name=self.text
                    print("签名内容为:"+name)


    def draw(self, screen: pygame.surface.Surface):
        txtSurface = self.font.render(
            self.text, True, self.color)
        width = max(200, txtSurface.get_width()+10)  # 当文字过长时,延长文本框
        self.boxBody.w = width
        screen.blit(txtSurface, (self.boxBody.x+5, self.boxBody.y+5))
        pygame.draw.rect(screen, self.color, self.boxBody, 2)

#创建游戏窗口
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("XiaoXiong SingnalName")
#定义游戏变量
game_paused = False
#定义字体
font = pygame.font.SysFont("华文楷体", 40)
font1= pygame.font.SysFont("华文楷体", 15)
#定义颜色
TEXT_COL = (255, 255, 255)
#加载图片
resume_img = font.render("生成签名", True, TEXT_COL)
restaet_img = font.render("小熊制作", True, TEXT_COL)
quit_img = font.render("退出程序", True, TEXT_COL)

num = font.render("签名序号:", True, TEXT_COL)
name = font.render("签名内容:", True, TEXT_COL)

#创建实例
resume_button = button_new.Button(60, 500, resume_img, 1)
restart_button = button_new.Button(330, 500, restaet_img, 1)
quit_button = button_new.Button(600, 500, quit_img, 1)

inputbox_num = InputBox(pygame.Rect(155, 95, 2, 32))  # 输入框
inputbox_name = InputBox1(pygame.Rect(485, 95, 2, 32))


def draw_text(text, font, text_col, x, y):
  img = font.render(text, True, text_col)
  screen.blit(img, (x, y))
#游戏循环
run = True
screen.fill((52, 78, 91))
while run:
  #判断游戏是否暂停
  if game_paused == True:
    #判断游戏状态
      draw_text("小熊个性签名在线生成", font, TEXT_COL, 200, 10)
      draw_text("1:艺术签 2:连笔签 3:商务签 4:楷书签 5:潇洒签 6:草体签 7:行书签 8:个性签 9:可爱签", font1, TEXT_COL, 90, 60)
      draw_text("签名序号:", font1, TEXT_COL, 80, 100)
      draw_text("签名内容:", font1, TEXT_COL, 400, 100)
      inputbox_num.draw(screen)
      inputbox_name.draw(screen)
      #在屏幕画按钮

      if resume_button.draw(screen):
          if int(a) not in range(1,10):
              msgbox(msg='输入有误:\n抱歉,你输入的签名字体暂不存在,系统已将你刚才输入的字体:'+a+".ttf"+'已改为默认改为1.ttf号字体(艺术签),如果需要继续使用,请在文本提示框内修改'
                 '你的签名序号,谢谢!\n(Sorry, the signature font you entered does not currently exist. The system has changed the font you '
               'just entered: '+a+'.ttf to a default font of 1.ttf point (art label). If you need to continue using it, please modify it in the '
                 'text prompt box.)', title =' 温馨提示', ok_button='OK', image=None)
              a="1"
          headers = {
              "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36"}
          url = "http://www.uustv.com/"
          print("最终签名内容为:"+name)
          if int(a) > 0 and int(a) < 4:
              a = int(a)
          elif int(a) > 3 and int(a) < 7:
              a = int(a) - 3
          elif int(a) == 7 or int(a) == 8 or int(a)==9:
              a = int(8)
          from_data = {
              "word": name,
              "sizes": "60",
              "fonts": str(a) + ".ttf"
          }
          res = requests.post(url, data=from_data, headers=headers)
          text1 = res.content.decode()
          soup = BeautifulSoup(text1, "lxml")
          img_list = soup.find_all('img')
          url_img = img_list[0].get('src')
          img_message = requests.get("http://www.uustv.com/" + url_img, headers=headers)
          with open(name+".png", "wb") as file:
              file.write(img_message.content)
          imp = pygame.image.load(str(name)+".png").convert()
          screen.blit(imp, (130, 180))
      if restart_button.draw(screen):
          pass
      if quit_button.draw(screen):
        run = False
  else:
    draw_text("欢迎来到在线个性生成签名系统", font, TEXT_COL, 130, 150)
    draw_text("为防止机器操作,请输入空格键进入系统", font, TEXT_COL, 50, 270)
  #事件处理器
  for event in pygame.event.get():
      inputbox_num.dealEvent(event)
      inputbox_name.dealEvent(event)
      if event.type == pygame.KEYDOWN:
          if event.key == pygame.K_SPACE:
              game_paused = True
              screen.fill((52, 78, 91))
      if event.type == pygame.QUIT:
          run = False
  pygame.display.flip()
if quit_button.draw(screen):
    run = False
pygame.quit()

部分截图:

 

 

 

 

 

 到此结束了,需要这个简单项目文件的可以私我,看到会第一时间回复!

猜你喜欢

转载自blog.csdn.net/Abtxr/article/details/129828348