|
发表于 2023-12-13 23:30:23
From FishC Mobile
|
显示全部楼层
|阅读模式
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Python 写一个悬浮桌面上的倒计时器
要求:
1.半透明
2.悬浮
3.倒计时长可以设定
4.无边框
这是一个有趣的项目!为了实现这个悬浮桌面上的倒计时器,我们可以使用Python中的Tkinter库和Win32gui库。
首先,你需要安装Win32gui库。可以使用以下命令通过pip进行安装:
然后,你可以尝试以下代码:
- import tkinter as tk
- import win32gui
- class CountdownTimer:
- def __init__(self, duration):
- self.duration = duration
- self.root = tk.Tk()
- self.root.overrideredirect(1) # 隐藏标题栏
- self.root.attributes("-alpha", 0.8) # 设置透明度
- self.root.attributes("-topmost", True) # 窗口置顶
- # 获取屏幕宽高
- screen_width = self.root.winfo_screenwidth()
- screen_height = self.root.winfo_screenheight()
- # 计算窗口位置
- x = int(screen_width / 2)
- y = int(screen_height / 2)
- # 创建标签并添加到窗口
- self.label = tk.Label(self.root, text=self.get_time(), font=("Arial", 36))
- self.label.pack()
- # 设置窗口位置
- self.root.geometry("+{}+{}".format(x, y))
- # 更新倒计时
- self.update_timer()
- def update_timer(self):
- if self.duration <= 0:
- self.label.config(text="Time's up!")
- self.root.after(2000, self.close_window) # 显示 "Time's up!" 两秒后关闭窗口
- else:
- self.label.config(text=self.get_time())
- self.duration -= 1
- self.root.after(1000, self.update_timer) # 每一秒更新一次倒计时
- def get_time(self):
- minutes = self.duration // 60
- seconds = self.duration % 60
- return "{:02d}:{:02d}".format(minutes, seconds)
- def close_window(self):
- self.root.destroy()
- def set_transparent(hwnd):
- # 设置窗口透明度为20%
- win32gui.SetWindowLong(hwnd, win32gui.GWL_EXSTYLE,
- win32gui.GetWindowLong(hwnd, win32gui.GWL_EXSTYLE) | win32gui.WS_EX_LAYERED)
- win32gui.SetLayeredWindowAttributes(hwnd, win32gui.RGB(0, 0, 0), 0, win32gui.LWA_ALPHA)
- if __name__ == "__main__":
- timer = CountdownTimer(180) # 设置倒计时时长为3分钟
- # 获取窗口句柄
- hwnd = int(timer.root.winfo_id())
- # 设置窗口半透明
- set_transparent(hwnd)
- # 进入事件循环
- timer.root.mainloop()
复制代码
这段代码会创建一个指定时长的倒计时器窗口,并设定其半透明、悬浮、无边框等特性。你可以通过修改`CountdownTimer`类中的`duration`参数来设置倒计时时长。
希望这个例子能满足你的需求!如果有任何问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|
|