Carson's Travels - 章鱼漫游记

一些关于旅行的东东 | Adventure travel around the world

Test VBA

import os

from datetime import datetime

import win32com.client

import tkinter as tk

from PIL import Image, ImageTk


# 更新进度文本框

def update_progress(message, tag=None):

    text_box.insert(tk.END, message + '\n')

    

    if tag:

        text_box.tag_config("pass", foreground="green", font=("Arial", 10, "bold"))

        text_box.tag_config("fail", foreground="red", font=("Arial", 10, "bold"))

        if tag == "pass":

            text_box.tag_add("pass", "end-2l linestart", "end-1l")

        elif tag == "fail":

            text_box.tag_add("fail", "end-2l linestart", "end-1l")

    

    text_box.see(tk.END)


# 保存附件

def save_attachment(attachment, path):

    try:

        attachment.SaveAsFile(path)

        update_progress(f"Saved attachment to {path}", tag="pass")

    except Exception as e:

        update_progress(f"Error saving attachment to {path}: {e}", tag="fail")


# 处理文件名中的特殊字符

def sanitize_filename(filename):

    return "".join(c for c in filename if c.isalnum() or c in (' ', '.', '_')).rstrip()


# 检查并保存附件

def check_and_save_attachments():

    update_progress("Starting to check and save attachments...")


    try:

        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

        inbox = outlook.GetDefaultFolder(6)  # 6 corresponds to the inbox

    except Exception as e:

        update_progress(f"Error accessing Outlook: {e}", tag="fail")

        return


    box2024_folder = None

    for folder in inbox.Folders:

        if folder.Name == 'Box2024':

            box2024_folder = folder

            break


    if not box2024_folder:

        update_progress("Box2024 folder not found in Outlook", tag="fail")

        return


    attachment_folder = os.path.join('data', 'Rawbox2024')

    if not os.path.exists(attachment_folder):

        os.makedirs(attachment_folder)


    try:

        messages = box2024_folder.Items

    except Exception as e:

        update_progress(f"Error accessing Box2024 folder items: {e}", tag="fail")

        return


    num_messages = len(messages)

    update_progress(f"Total number of messages in Box2024: {num_messages}")


    csv_files_to_save = []

    for message in messages:

        for attachment in message.Attachments:

            if attachment.FileName.endswith('.csv'):

                sanitized_filename = sanitize_filename(attachment.FileName)

                new_filename = os.path.join(

                    attachment_folder,

                    f"{os.path.splitext(sanitized_filename)[0]}_{datetime.now().strftime('%d%m%y')}.csv"

                )

                if not os.path.exists(new_filename):

                    csv_files_to_save.append((attachment, new_filename))


    total_files = len(csv_files_to_save)

    update_progress(f"Total number of new CSV files to save: {total_files}")


    for idx, (attachment, new_filename) in enumerate(csv_files_to_save, 1):

        update_progress(f"Saving attachment {idx}/{total_files}: {new_filename}")

        save_attachment(attachment, new_filename)


    update_progress("Finished saving all attachments", tag="pass")


# 新的 check_and_save_attachments 函数

def check_csv_files():

    update_progress("Checking and saving CSV files from Outlook Box2024 folder...")

    check_and_save_attachments()


# 获取用户名

def get_username():

    import ctypes

    GetUserNameEx = ctypes.windll.secur32.GetUserNameExW

    NameDisplay = 3

    size = ctypes.pointer(ctypes.c_ulong(0))

    GetUserNameEx(NameDisplay, None, size)

    buffer = ctypes.create_unicode_buffer(size.contents.value)

    GetUserNameEx(NameDisplay, buffer, size)

    return buffer.value


# 获取当前日期和星期几

current_date = datetime.now().strftime("%d, %b %Y")

current_weekday = datetime.now().strftime("%A")


# 计算距离周末的天数

def days_until_weekend():

    today = datetime.now()

    current_weekday = today.weekday()  # Monday is 0 and Sunday is 6

    if current_weekday < 5:  # If today is not Saturday or Sunday

        days_left = 5 - current_weekday  # Calculate days until Saturday

    else:

        days_left = 0  # If today is Saturday or Sunday

    return days_left


days_left = days_until_weekend()

weekend_message = "今天就是周末!" if days_left == 0 else f"距离周末还有 {days_left} 天"


# 创建主窗口

root = tk.Tk()

root.title("欢迎界面")


# 创建菜单栏

menu_bar = tk.Menu(root)

root.config(menu=menu_bar)


# 添加文件菜单

file_menu = tk.Menu(menu_bar, tearoff=0)

menu_bar.add_cascade(label="文件", menu=file_menu)

file_menu.add_command(label="打开")

file_menu.add_command(label="保存")

file_menu.add_separator()

file_menu.add_command(label="退出", command=root.quit)


# 添加帮助菜单

help_menu = tk.Menu(menu_bar, tearoff=0)

menu_bar.add_cascade(label="帮助", menu=help_menu)

help_menu.add_command(label="关于")


# 创建画布并显示顶部图片 banner 和欢迎信息

canvas = tk.Canvas(root, width=600, height=100)

canvas.pack(side=tk.TOP, pady=10, anchor=tk.N)


# 加载并显示 banner 图片

banner_image = tk.PhotoImage(file="path_to_your_banner_image.png")

canvas.create_image(0, 0, anchor=tk.NW, image=banner_image)


# 保持对图片对象的引用

canvas.banner_image = banner_image


# 使用 PIL 加载并调整第二张图片的大小

overlay_image_path = "path_to_your_overlay_image.png"

overlay_image = Image.open(overlay_image_path)

overlay_image = overlay_image.resize((100, 30), Image.ANTIALIAS)  # 调整大小


# 将 PIL 图像转换为 PhotoImage

overlay_photo = ImageTk.PhotoImage(overlay_image)

canvas.create_image(150, 0, anchor=tk.NW, image=overlay_photo)


# 保持对叠加图片对象的引用

canvas.overlay_image = overlay_photo


# 获取用户名

username = get_username()


# 在图片上显示欢迎信息

welcome_line1 = f"欢迎 {username},今天是 {current_date} {current_weekday}。"

welcome_line2 = f"{weekend_message}"


# 手动控制行间距

line_spacing = 20  # 行间距(像素)


# 左对齐文本

canvas.create_text(10, 15, text=welcome_line1, font=("Arial", 12), fill="black", anchor=tk.W)

canvas.create_text(10, 15 + line_spacing, text=welcome_line2, font=("Arial", 12), fill="black", anchor=tk.W)


# 创建检测进度文本框和滚动条框架

main_frame = tk.Frame(root)

main_frame.pack(side=tk.TOP, pady=10, padx=10, anchor=tk.NW)


text_frame = tk.Frame(main_frame)

text_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)


scrollbar = tk.Scrollbar(text_frame)

scrollbar.pack(side=tk.RIGHT, fill=tk.Y)


text_box = tk.Text(text_frame, width=80, height=10, yscrollcommand=scrollbar.set)  # 调整文本框大小

text_box.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)


scrollbar.config(command=text_box.yview)


# 创建按钮和说明框架,并将其放置在文本框的右侧

button_explain_frame = tk.Frame(main_frame)

button_explain_frame.pack(side=tk.LEFT, padx=10, fill=tk.Y)


# 创建按钮和说明文本框

def create_button_with_explanation(parent, button_text, button_command, explanation_text):

    frame = tk.Frame(parent)

    frame.pack(fill=tk.X, pady=5)


    button = tk.Button(frame, text=button_text, command=button_command, width=12, height=3)

    button.pack(side=tk.TOP)


    explanation = tk.Label(frame, text=explanation_text, wraplength=300, justify=tk.LEFT)

    explanation.pack(side=tk.TOP, pady=(5, 0))


# 创建按钮和对应的说明

create_button_with_explanation(button_explain_frame, "Verify", run_checks, "This button will start the verification process.")

create_button_with_explanation(button_explain_frame, "Check CSV", check_csv_files, "This button will save new CSV attachments from Outlook Box2024 folder to the local data\\Rawbox2024 folder.")


# 创建底部状态栏

status_bar = tk.Label(root, text="状态栏", bd=1, relief=tk.SUNKEN, anchor=tk.W)

status_bar.pack(side=tk.BOTTOM, fill=tk.X)


# 运行主循环

root.mainloop()


Powered By Z-BlogPHP 1.7.3

2024 Carson's Travels - 章鱼漫游记 - WWW.CARSONX.COM All Rights Reserved.