欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

更新 - Python 操作系统

最编程 2024-10-04 07:23:21
...

更新日志(2024-10-3  13:56):

  • 此次更新主要是将按钮替换为图片,在观感上会更好看一些
  • 增添修改名称【change_app_name】函数,用于修改应用名称

相关代码:

import os
import tkinter as tk
from tkinter import messagebox, simpledialog
from PIL import Image, ImageTk

def open_cumputer_app():
    print("打开此电脑")

def attribute_cumputer_app():
    print("查看此电脑属性")

def delete_cumputer_app():
    print("删除此电脑图标")

def change_app_name():
    new_name = simpledialog.askstring("输入名称", "请输入新的名称:")
    if new_name:
        print(f"名称已更改为: {new_name}")
        # 如果需要更新界面上的名字,可以在这里进行操作
        name_label.config(text=new_name)

def show_popup(menu, event):
    menu.post(event.x_root, event.y_root)

def on_double_click_computer_button(event):
    open_cumputer_app()

# 创建主窗口
root = tk.Tk()
root.title("Desktop Application")
root.geometry("800x600")

# 获取当前文件所在目录
current_dir_file_data = os.path.dirname(__file__)

# 加载此电脑图片
icon_width, icon_height = 64, 64  # 图标大小
computer_button_img = Image.open(os.path.join(current_dir_file_data,'data', "应用图标", "此电脑.jpg"))
computer_button_img = computer_button_img.resize((icon_width, icon_height), Image.LANCZOS)  # 调整图片大小
computer_button_image = ImageTk.PhotoImage(computer_button_img)

# 创建一个 Frame 用于放置图片和应用名称
app_frame = tk.Frame(root)
app_frame.place(x=10, y=10)

# 创建一个 Label 用于放置图片
image_label = tk.Label(app_frame, image=computer_button_image)
image_label.image = computer_button_image  # 保持对 PhotoImage 的引用,避免被垃圾回收
image_label.grid(row=0, column=0, sticky="nsew")

# 创建一个 Label 用于显示应用名称
name_label = tk.Label(app_frame, text="此电脑", font=("Arial", 10))
name_label.grid(row=1, column=0, sticky="nsew")

# 创建一个弹出菜单
menu_cumputer_app = tk.Menu(root, tearoff=0)  # 用于应用软件的右键菜单

# 应用软件右键菜单项
menu_cumputer_app.add_command(label="打开", command=open_cumputer_app)
menu_cumputer_app.add_command(label="属性", command=attribute_cumputer_app)
menu_cumputer_app.add_separator()
menu_cumputer_app.add_command(label="删除", command=delete_cumputer_app)
menu_cumputer_app.add_command(label="修改名称", command=change_app_name)

# 绑定右键点击事件
image_label.unbind("<Button-3>")  # 取消之前的绑定
image_label.bind("<Button-3>", lambda event: show_popup(menu_cumputer_app, event))  # 使用应用菜单
image_label.bind("<Double-Button-1>", on_double_click_computer_button)  # 绑定左键双击

# 运行主循环
root.mainloop()

注:要在指定的路径下放置图片,不然会报错,后续会整理到源码中