【玩转python】使用python让窗口动起来

一开始想写一个倒计时器,后来想到时间到了只是提示个框不太好,得加入抖动效果,说干就干
`import tkinter as tk
from tkinter import messagebox
import ctypes
import random
import time

定义 RECT 结构体

class RECT(ctypes.Structure):
fields = [
("left", ctypes.c_long),
("top", ctypes.c_long),
("right", ctypes.c_long),
("bottom", ctypes.c_long)
]

def shake_screen():
# 加载 user32.dll
user32 = ctypes.windll.user32

# 获取当前活动窗口的句柄
hwnd = user32.GetForegroundWindow()

# 设置抖动参数
shakes = 10
degree = 10

# 创建 RECT 结构体实例
rect = RECT()

# 获取当前窗口的位置
# 调用 GetWindowRect 函数
result = user32.GetWindowRect(hwnd, ctypes.byref(rect))
if result:
    # 输出窗口的位置和大小
    x_center = (rect.left + rect.right) // 2
    y_center = (rect.top + rect.bottom) // 2
    width = rect.right - rect.left
    height = rect.bottom - rect.top
    print(f"窗口位置: ({rect.left}, {rect.top})")
    print(f"窗口大小: 宽度 = {width}, 高度 = {height}")
else:
    print("获取窗口矩形信息失败")
for _ in range(shakes):
    for _ in range(100):
        x_offset = random.randint(-degree, degree)
        y_offset = random.randint(-degree, degree)
        ctypes.windll.user32.SetWindowPos(hwnd, 0, x_center + x_offset, y_center + y_offset, width, height, 0x0040)
        time.sleep(0.01)

# 恢复到原来的位置
ctypes.windll.user32.SetWindowPos(hwnd, 0, rect.left, rect.top, width, height, 0x0040)

def update_timer():
global timer_running
if time_left.get() > 0:
time_left.set(time_left.get() - 1)
root.after(1000, update_timer)
else:
timer_running = False
# messagebox.showinfo("时间到啦!", "开始震动.") 这里如果加了这个提示,相当于只是震动计时器自身,如果没有它,则是任意当前窗口,提醒效果相当哇塞
shake_screen()

def start_timer():
global timer_running
if not timer_running:
hours = int(entry_hours.get())
minutes = int(entry_minutes.get())
seconds = int(entry_seconds.get())
total_seconds = hours * 3600 + minutes * 60 + seconds
time_left.set(total_seconds)
timer_running = True
update_timer()

初始化主窗口

root = tk.Tk()
root.title("振你一下倒计时器")

这里取消掉窗口的最大最小化按钮,要不然窗口太小标题显示不全,而且也不用最大最小化

root.resizable(False, False)
root.attributes('-toolwindow', True)

创建和放置标签和输入框

tk.Label(root, text="时:").grid(row=0, column=0)
entry_hours = tk.Entry(root)
entry_hours.grid(row=0, column=1)

tk.Label(root, text="分:").grid(row=1, column=0)
entry_minutes = tk.Entry(root)
entry_minutes.grid(row=1, column=1)

tk.Label(root, text="秒:").grid(row=2, column=0)
entry_seconds = tk.Entry(root)
entry_seconds.grid(row=2, column=1)

创建和放置开始按钮

start_button = tk.Button(root, text="开始", command=start_timer)
start_button.grid(row=3, column=0, columnspan=2)

创建和放置倒计时显示

time_left = tk.IntVar()
tk.Label(root, text="时间剩余:").grid(row=4, column=0)
tk.Label(root, textvariable=time_left).grid(row=4, column=1)

初始化倒计时状态

timer_running = False

运行主循环

root.mainloop()`

上面代码实现难点在于winapi的调用,需要创建一个RECT结构体接一下,其他没啥难度

posted @ 2025-03-18 09:22  高桥名人救生圈  阅读(63)  评论(0)    收藏  举报