Python 实现小车移动动画:从左上角到右下角匀速移动
以下是完成上述要求的 Python 代码:
import tkinter as tk
from tkinter import messagebox
import threading
from PIL import Image, ImageTk
import os
import ctypes
# 获取屏幕尺寸
user32 = ctypes.windll.user32
screen_width = user32.GetSystemMetrics(0)
screen_height = user32.GetSystemMetrics(1)
# 创建窗口
window = tk.Tk()
window.title('小车移动')
window.geometry('500x500')
window.protocol('WM_DELETE_WINDOW', window.iconify)
# 添加菜单
menu = tk.Menu(window)
window.config(menu=menu)
def restore_window():
window.deiconify()
def quit_program():
window.quit()
window.destroy()
menu.add_command(label='恢复', command=restore_window)
menu.add_command(label='退出', command=quit_program)
# 加载小车图片
current_dir = os.path.dirname(os.path.abspath(__file__))
car_image_path = os.path.join(current_dir, 'car.png')
car_image = Image.open(car_image_path)
car_image = car_image.resize((100, 100))
car_photo = ImageTk.PhotoImage(car_image)
# 创建小车标签
car_label = tk.Label(window, image=car_photo)
car_label.pack()
# 设置小车移动速度
move_speed = tk.IntVar()
move_speed.set(5)
# 创建速度调节器
speed_label = tk.Label(window, text='移动速度')
speed_label.pack()
speed_scale = tk.Scale(window, from_=1, to=10, orient=tk.HORIZONTAL, variable=move_speed)
speed_scale.pack()
# 设置小车初始位置
car_x = 0
car_y = 0
def move_car():
global car_x, car_y
while car_x < screen_width and car_y < screen_height:
car_x += move_speed.get()
car_y += move_speed.get()
car_label.place(x=car_x, y=car_y)
window.update()
# 控制小车移动速度
window.after(100 - move_speed.get() * 10)
# 创建线程用于移动小车
move_thread = threading.Thread(target=move_car)
def start_move():
# 启动移动线程
move_thread.start()
def stop_move():
# 停止移动线程
move_thread.join()
# 创建开始和停止按钮
start_button = tk.Button(window, text='开始', command=start_move)
start_button.pack()
stop_button = tk.Button(window, text='停止', command=stop_move)
stop_button.pack()
# 运行窗口
window.mainloop()
在运行上述代码之前,需要确保安装了tkinter和Pillow库。
此代码创建了一个窗口,加载了一张小车图片,并提供了开始和停止按钮来控制小车的移动。可以通过调节速度调节器来改变小车的移动速度。点击关闭按钮后,程序将最小化到托盘区,右键点击托盘区图标可以恢复程序或退出程序。
原文地址: http://www.cveoy.top/t/topic/bJ3y 著作权归作者所有。请勿转载和采集!