以下是使用Python语言实现的代码:

import tkinter as tk
from PIL import Image, ImageTk
import time
import threading
import sys
from tkinter import messagebox
import os
import ctypes
import win32con
import win32gui

class CarWindow(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('Car Window')
        self.geometry('500x500')
        self.resizable(False, False)
        self.protocol('WM_DELETE_WINDOW', self.on_close)
        self.iconify()
        self.create_tray_icon()

        self.canvas = tk.Canvas(self, width=500, height=500)
        self.canvas.pack()

        self.car_image = ImageTk.PhotoImage(file='car.png')  # 替换为你的小车图片路径
        self.car = self.canvas.create_image(0, 0, anchor='nw', image=self.car_image)

        self.speed = 5  # 默认速度为5

        self.move_car()

    def create_tray_icon(self):
        self.tray_icon = tk.Tk()
        self.tray_icon.withdraw()

        self.tray_menu = tk.Menu(self.tray_icon, tearoff=0)
        self.tray_menu.add_command(label='恢复', command=self.restore)
        self.tray_menu.add_command(label='退出', command=self.exit)

        self.tray_icon.bind('<Button-1>', self.restore)
        self.tray_icon.bind('<Button-3>', self.tray_icon_menu)

        self.tray_icon.iconbitmap('icon.ico')  # 替换为你的图标路径

    def tray_icon_menu(self, event):
        self.tray_menu.post(event.x_root, event.y_root)

    def restore(self, event=None):
        self.deiconify()
        self.tray_icon.withdraw()

    def exit(self):
        self.tray_icon.quit()
        self.destroy()
        sys.exit()

    def on_close(self):
        self.iconify()
        self.tray_icon.deiconify()

    def move_car(self):
        x, y = self.canvas.coords(self.car)
        if x >= 500 or y >= 500:
            self.canvas.coords(self.car, 0, 0)
        else:
            self.canvas.move(self.car, self.speed, self.speed)
        self.after(50, self.move_car)

if __name__ == '__main__':
    app = CarWindow()
    app.mainloop()

请注意,上述代码中的car.pngicon.ico分别代表小车图片和程序图标,请将其替换为你实际使用的图片和图标路径。

在运行代码之前,需要先安装tkinterPillow库,可以使用以下命令进行安装:

pip install tk
pip install pillow

运行代码后,会弹出一个小车在指定窗口区域从左上角到右下角匀速移动的窗口。点击关闭按钮后,程序将转入后台执行,程序图标会出现在任务栏托盘区。右键点击托盘区图标,可以选择恢复程序运行或退出程序。

Python实现小车匀速移动,支持后台运行和托盘菜单

原文地址: https://www.cveoy.top/t/topic/bKa2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录