PyMe用户技术论坛

🏠 ← 返回首页

[求助] 在tkinter模块中手动签名项目代码在PyMe怎样使用

头像 269064737 积分: 4
2025-07-09 08:07:18

import pyme

from pyme import canvas

import os

from PIL import Image


class SignatureApp:

  def __init__(self):

    # 创建主窗口

    self.window = pyme.Window("手动签名画布", 800, 600)

     

    # 创建画布

    self.canvas = canvas.Canvas(self.window, 600, 400)

    self.canvas.position = (100, 100)

    self.canvas.background = (255, 255, 255) # 白色背景

     

    # 绘图变量

    self.last_x = None

    self.last_y = None

    self.line_width = 3

    self.drawing = False

     

    # 创建按钮

    self.clear_btn = pyme.Button("清除", (100, 520), (100, 50))

    self.save_btn = pyme.Button("保存签名", (250, 520), (100, 50))

    self.exit_btn = pyme.Button("退出", (400, 520), (100, 50))

     

    # 绑定事件

    self.canvas.on_mouse_press = self.on_mouse_press

    self.canvas.on_mouse_release = self.on_mouse_release

    self.canvas.on_mouse_move = self.on_mouse_move

    self.clear_btn.on_click = self.clear_canvas

    self.save_btn.on_click = self.save_signature

    self.exit_btn.on_click = self.exit_app

     

    # 运行主循环

    self.window.main_loop()

   

  def on_mouse_press(self, x, y, button):

    if button == "left":

      self.drawing = True

      self.last_x = x

      self.last_y = y

   

  def on_mouse_release(self, x, y, button):

    if button == "left":

      self.drawing = False

      self.last_x = None

      self.last_y = None

   

  def on_mouse_move(self, x, y):

    if self.drawing and self.last_x is not None and self.last_y is not None:

      self.canvas.draw_line((self.last_x, self.last_y), (x, y), 

                width=self.line_width, color=(0, 0, 0))

      self.last_x = x

      self.last_y = y

   

  def clear_canvas(self):

    self.canvas.clear()

   

  def save_signature(self):

    # 获取画布像素数据

    pixels = self.canvas.get_pixels()

     

    # 创建PIL图像

    img = Image.new("RGB", (self.canvas.width, self.canvas.height))

    img.putdata([(r, g, b) for (r, g, b, a) in pixels])

     

    # 保存图像

    if not os.path.exists("signatures"):

      os.makedirs("signatures")

     

    filename = f"signatures/signature_{len(os.listdir('signatures')) + 1}.png"

    img.save(filename)

    print(f"签名已保存为: {filename}")

   

  def exit_app(self):

    self.window.close()


if __name__ == "__main__":

  app = SignatureApp()

回复

头像 admin 积分: 8
2025-07-17 23:51:58

我正计划支持导入

登录后才能回复帖子