【教程】使用ChatGPT制作基于Tkinter的桌面时钟

news/2025/2/12 14:08:51/

目录

描述

代码

效果

说明

下载

开源链接:GitHub - 1061700625/Tkinter_Desktop_Clock: 基于Tkinter的桌面时钟小工具

描述

        给ChatGPT的描述内容:

        python在桌面上显示动态的文字,不要显示窗口边框。窗口背景和标签背景都是透明的,但标签内的文字是有颜色。使用tkinter库实现,并以class的形式书写,方便用户对内容进行扩展开发。

        窗口默认出现在屏幕的中间位置。窗口中的标签需要包含两项内容。其中一项用于实时显示当前的日期和时间,精确到毫秒。另一项从txt文件中读取显示,若没有txt文件则显示“None”。

        在未锁定状态下,鼠标可以拖动窗口。在锁定状态下,窗口无法通过鼠标的拖动而移动。在窗口中添加一个“锁定”按钮,当鼠标移动到窗口上方时,显示“锁定”按钮,鼠标移走后,隐藏“锁定”按钮。通过“锁定”按钮,窗口进入锁定状态。在锁定状态下,当鼠标移动到窗口上方时,显示一个“解除锁定”的按钮,鼠标移走后,隐藏该“解除锁定”按钮。通过点击“解除锁定”按钮,进入未锁定状态。锁定和未锁定状态是互相切换的。

        给窗口添加一个鼠标右键的功能,在右键菜单中,可以点击“退出”,从而退出应用。

        窗口中的内容居中显示。

        添加 右键窗口显示“改变颜色”子菜单,点击后,弹出颜色选择框,通过选择不同的颜色,可以改变窗口的背景颜色。

        添加 右键窗口显示“置顶”子菜单,点击后,可以使当前窗口一直保持在最前面。在置顶状态下,再右键窗口,改为显示“取消置顶”。

        添加右键“修改日期”子菜单,点击后,弹出开始日期选择框和结束日期选择框,选择完毕后,更新到self.start_date和self.end_date,并立即调用update_note_label函数。

        添加 右键窗口显示“修改note”子菜单,点击后,弹出内容输入框,输入框默认显示“小锋学长生活大爆炸”。点击确认后,输入框的内容更新到self.text_label。只需要给出修改的关键代码。

        启动时从http://xfxuezhang.cn/web/share/version获取desktop_clock.txt文件,根据内容与当前版本是否一致,若不一致则弹窗提示有更新。

        添加右键“开机自启动”选项,设置后,允许pc开机后自动启动当前软件。并且,当设置了开机自启动后,再次点击,应该需要 取消开机自启动。

        将一些配置参数存放入注册表中,在启动软件时,从注册表中读取参数,并更新到软件中。当用户在软件中更改了配置时,需要将改动更新到注册表中。

代码

给出的代码,并经过微调:

import tkinter as tk
import datetime
import math
import locale
import os, sys
from tkinter.colorchooser import askcolor
import webbrowser
import tkinter.messagebox as messagebox
import tkinter.ttk as ttk
import tkcalendar
import babel.numbers
import requests
import tkinter.simpledialog
import winreg# Set the locale to use UTF-8 encoding
locale.setlocale(locale.LC_ALL, 'en_US.utf8')
VERSION = '20230406'
CONFIG_REG_PATH = r'SOFTWARE\desktop_clock\Settings'class TransparentWindow(tk.Tk):def __init__(self, text_file=None):super().__init__()self.attributes('-alpha', 1) # 设置窗口透明度# self.attributes('-topmost', True) # 窗口置顶# self.attributes('-transparentcolor', '#000000')self.overrideredirect(True) # 去掉窗口边框self.locked = False # 初始化锁定状态self.mouse_x = 0self.mouse_y = 0self.config(bg='#000000', highlightthickness=0, bd=0)self.window_width = 400self.window_height = 100# # 获取屏幕尺寸和窗口尺寸,使窗口居中# screen_width = self.winfo_screenwidth()# screen_height = self.winfo_screenheight()# x = (screen_width - self.window_width) // 2# y = (screen_height - self.window_height) // 2# self.geometry('{}x{}+{}+{}'.format(self.window_width, self.window_height, x, y))# 添加日期时间标签self.datetime_label = tk.Label(self, text='', font=('Arial', 20), fg='#FFFFFF', bg='#000000')self.datetime_label.place(relx=0.5, y=20, anchor='center')# 提示标签self.note_label = tk.Label(self, text='123', font=('Arial', 14), fg='#FFFFFF', bg='#000000')self.note_label.place(relx=0.5, y=50, anchor='center')# 文本标签self.text_label = tk.Label(self, text='', font=('Arial', 14), fg='#FFFFFF', bg='#000000')self.text_label.place(relx=0.5, y=80, anchor='center')# 添加锁定按钮self.lock_button = tk.Button(self, text='锁定', font=('Arial', 10), command=self.toggle_lock)self.toggle_lock_button(True)self.toggle_lock_button(False)# 添加解锁按钮self.unlock_button = tk.Button(self, text='解除锁定', font=('Arial', 10), command=self.toggle_lock)self.toggle_unlock_button(True)self.toggle_unlock_button(False)# 绑定鼠标事件self.bind('<Button-1>', self.on_left_button_down)self.bind('<ButtonRelease-1>', self.on_left_button_up)self.bind('<B1-Motion>', self.on_mouse_drag)self.bind('<Enter>', self.on_mouse_enter)self.bind('<Leave>', self.on_mouse_leave)# 创建右键菜单self.menu = tk.Menu(self, tearoff=0)self.menu.add_command(label="退出应用", command=self.quit)# 添加“置顶”子菜单self.menu.add_command(label="窗口置顶", command=self.topmost_on)# 添加“改变颜色”子菜单self.menu.add_command(label="修改颜色", command=self.choose_color)# 添加“修改日期”子菜单self.menu.add_command(label="修改日期", command=self.modify_date)# 添加“修改note”子菜单self.menu.add_command(label='修改Note', command=self.edit_text_labele)# 添加“开机自启动”子菜单self.menu.add_command(label="开机自启", command=self.toggle_startup)# 添加“恢复出厂设置”子菜单self.menu.add_command(label="恢复设置", command=self.init_config_to_registry)# 添加“关于”子菜单self.menu.add_command(label="关于我们", command=self.about_me)self.bind("<Button-3>", self.show_menu)self.update_config_from_registry()# 定时更新日期时间标签self.update_datetime()# 定时更新text标签self.update_text_label()# 定时更新note标签self.update_note_label()self.check_version()def update_config_from_registry(self):# Get settings from registry or set default valuesself.start_date = self.get_value_from_registry('start_date', '2023/2/20', write=True)self.end_date = self.get_value_from_registry('end_date', '2023/7/9', write=True)startup = self.get_value_from_registry('startup', False)self.menu.entryconfig(5, label='取消自动' if startup else '开机自启')topmost = self.get_value_from_registry('topmost', False)self.attributes('-topmost', True if topmost else False)self.menu.entryconfig(1, label='取消置顶' if topmost else '窗口置顶')background_color = self.get_value_from_registry('background_color', '#000000', write=True)self.config(bg=background_color)self.datetime_label.config(bg=background_color)self.note_label.config(bg=background_color)self.text_label.config(bg=background_color)self.locked = self.get_value_from_registry('lock', False)self.toggle_lock_button(False if self.locked else True)self.toggle_unlock_button(True if self.locked else False)self.text_label.configure(text=self.get_value_from_registry('text_label', '小锋学长生活大爆炸', write=True))screen_width = self.winfo_screenwidth()screen_height = self.winfo_screenheight()win_x = (screen_width - self.window_width) // 2win_y = (screen_height - self.window_height) // 2x = self.get_value_from_registry('win_x', str(win_x))y = self.get_value_from_registry('win_y', str(win_y))self.geometry('{}x{}+{}+{}'.format(self.window_width, self.window_height, x, y))def init_config_to_registry(self, first=False):self.set_value_to_registry('start_date', '2023/2/20')self.set_value_to_registry('end_date', '2023/7/9')self.set_value_to_registry('startup', None)self.set_value_to_registry('topmost', None)self.set_value_to_registry('background_color', '#000000')self.set_value_to_registry('lock', None)self.set_value_to_registry('text_label', '小锋学长生活大爆炸')screen_width = self.winfo_screenwidth()screen_height = self.winfo_screenheight()x = (screen_width - self.window_width) // 2y = (screen_height - self.window_height) // 2self.set_value_to_registry('win_x', str(x))self.set_value_to_registry('win_y', str(y))if not first:messagebox.showinfo("提示", "重启生效")def check_version(self):url = 'http://xfxuezhang.cn/web/share/version/desktop_clock.txt'try:resp = requests.get(url, timeout=2).text.strip()if resp != VERSION:if messagebox.askyesno('更新提示', '发现新版本,是否前往蓝奏云下载?密码:c9o1'):webbrowser.open('https://xfxuezhang.lanzouo.com/b09ubrasb')except:passdef get_value_from_registry(self, query, default=None, write=False, vtype=winreg.REG_SZ):# 从注册表中读取参数,如果没有,则使用默认值try:with winreg.OpenKey(winreg.HKEY_CURRENT_USER, CONFIG_REG_PATH, access=winreg.KEY_READ) as key:value = winreg.QueryValueEx(key, query)[0]except:value = defaultif write:# 将默认值存储到注册表中with winreg.CreateKey(winreg.HKEY_CURRENT_USER, CONFIG_REG_PATH) as key:winreg.SetValueEx(key, query, 0, vtype, default)return valuedef set_value_to_registry(self, query, value=None, vtype=winreg.REG_SZ):if value is not None:with winreg.CreateKey(winreg.HKEY_CURRENT_USER, CONFIG_REG_PATH) as key:winreg.SetValueEx(key, query, 0, vtype, value)else:try:with winreg.OpenKey(winreg.HKEY_CURRENT_USER, CONFIG_REG_PATH, access=winreg.KEY_ALL_ACCESS) as key:winreg.DeleteValue(key, query)except:passdef check_startup_enabled(self):key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",access=winreg.KEY_READ)app_path = os.path.abspath(sys.argv[0])app_name = os.path.basename(app_path)try:value, type = winreg.QueryValueEx(key, app_name)except WindowsError:return Falsereturn value == app_pathdef toggle_startup(self):key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",access=winreg.KEY_ALL_ACCESS)app_path = os.path.abspath(sys.argv[0])app_name = os.path.basename(app_path)if self.check_startup_enabled():winreg.DeleteValue(key, app_name)self.menu.entryconfig(5, label='开机自启')messagebox.showinfo("提示", "已取消开机自启动")else:winreg.SetValueEx(key, app_name, 0, winreg.REG_SZ, app_path)self.menu.entryconfig(5, label='取消自启')messagebox.showinfo("提示", "已设置开机自启动")key.Close()self.set_value_to_registry('startup', '1' if self.check_startup_enabled() else None)def about_me(self):# webbrowser.open_new_tab('http://www.xfxuezhang.cn')messagebox.showinfo("关于", "暂时没什么内容")# 选择日期def modify_date(self):top = tk.Toplevel(self)# 获取屏幕尺寸和窗口尺寸,使窗口居中screen_width = top.winfo_screenwidth()screen_height = top.winfo_screenheight()window_width = 175window_height = 100x = (screen_width - window_width) // 2y = (screen_height - window_height) // 2top.geometry('{}x{}+{}+{}'.format(window_width, window_height, x, y))top.title('选择日期')tk.Label(top, text='开始日期:').grid(row=0, column=0)start_date = tkcalendar.DateEntry(top, width=12, background='darkblue', foreground='white', date_pattern='yyyy/mm/dd', date=self.start_date, justify='center')start_date.grid(row=0, column=1)tk.Label(top, text='结束日期:').grid(row=1, column=0)end_date = tkcalendar.DateEntry(top, width=12, background='darkblue', foreground='white', date_pattern='yyyy/mm/dd', date=self.end_date, justify='center')end_date.grid(row=1, column=1)def update_dates():self.start_date = start_date.get_date().strftime('%Y/%m/%d')self.end_date = end_date.get_date().strftime('%Y/%m/%d')self.update_note_label()top.destroy()self.set_value_to_registry('start_date', self.start_date)self.set_value_to_registry('end_date', self.end_date)button = tk.Button(top, text="确定", command=update_dates)button.grid(row=2, column=0, columnspan=2, pady=10)# 窗口置顶def topmost_on(self):if self.attributes('-topmost'):self.attributes('-topmost', False)self.menu.entryconfig(1, label='窗口置顶')else:self.attributes('-topmost', True)self.menu.entryconfig(1, label='取消置顶')self.set_value_to_registry('topmost', '1' if self.attributes('-topmost') else None)# 改变背景色def choose_color(self):color = askcolor()[1]if color:self.config(bg=color)self.datetime_label.config(bg=color)self.note_label.config(bg=color)self.text_label.config(bg=color)self.set_value_to_registry('background_color', color)# 锁定def toggle_lock_button(self, show=True):if show:self.lock_button.place(relx=1, rely=0.85, anchor='e')else:self.lock_button.place_forget()# 解除锁定def toggle_unlock_button(self, show=True):if show:self.unlock_button.place(relx=1, rely=0.85, anchor='e')else:self.unlock_button.place_forget()# 锁定和解除锁定的切换def toggle_lock(self):if self.locked:self.locked = Falseself.toggle_lock_button(True)self.toggle_unlock_button(False)else:self.locked = Trueself.toggle_lock_button(False)self.toggle_unlock_button(True)self.set_value_to_registry('lock', '1' if self.locked else None)# self.set_value_to_registry('winfo_screenwidth', self.winfo_x() - self.mouse_x)# 显示右键菜单def show_menu(self, event):self.menu.post(event.x_root, event.y_root)# 更新日期时间def update_datetime(self):now = datetime.datetime.now().strftime('%Y-%m-%d     \u270d     %H:%M:%S.%f')[:-4]msg = f'{now}'self.datetime_label.configure(text=msg)self.after(10, self.update_datetime)# 更新txt文档内容def update_text_label(self):now = ''if os.path.exists('config.txt'):now = open('config.txt', 'r', encoding='utf8').read().strip()now = now or self.get_value_from_registry('text_label', '小锋学长生活大爆炸')if now:self.text_label.configure(text=now)# self.after(1000, self.update_text_label)def edit_text_labele(self):"""打开文本输入框并更新内容"""# 创建文本输入框并显示默认内容note = tkinter.simpledialog.askstring('修改Note', '请输入新的note', initialvalue=self.text_label['text'], parent=self)# 如果用户点击确认,则更新文本标签的内容if note:self.text_label['text'] = noteself.set_value_to_registry('text_label', note)# 更新周次def update_note_label(self):# 指定日期,格式为 年-月-日start_y, start_m, start_d = list(map(int, self.start_date.strip().split('/')))end_y, end_m, end_d = list(map(int, self.end_date.strip().split('/')))specified_start_date = datetime.date(start_y, start_m, start_d)specified_end_date = datetime.date(end_y, end_m, end_d)today = datetime.date.today()# 计算距离指定日期过了多少周start_delta = today - specified_start_datenum_of_weeks = math.ceil(start_delta.days / 7)# 计算距离指定日期剩余多少周end_delta = specified_end_date - todayremain_weeks = math.ceil(end_delta.days / 7)msg = f'当前第{num_of_weeks}周, 剩余{remain_weeks}周({end_delta.days}天)'self.note_label.configure(text=msg)self.after(1000*60, self.update_note_label)# 实现窗口拖动def on_left_button_down(self, event):self.mouse_x = event.xself.mouse_y = event.y# 实现窗口拖动def on_left_button_up(self, event):x = self.winfo_x() + event.x - self.mouse_xy = self.winfo_y() + event.y - self.mouse_yself.mouse_x = 0self.mouse_y = 0self.set_value_to_registry('win_x', str(x))self.set_value_to_registry('win_y', str(y))# 实现窗口拖动def on_mouse_drag(self, event):if not self.locked:x = self.winfo_x() + event.x - self.mouse_xy = self.winfo_y() + event.y - self.mouse_yself.geometry('+{}+{}'.format(x, y))def on_mouse_leave(self, event):self.lock_button.place_forget()self.unlock_button.place_forget()def on_mouse_enter(self, event):if not self.locked:self.toggle_lock_button(True)self.toggle_unlock_button(False)else:self.toggle_lock_button(False)self.toggle_unlock_button(True)if __name__ == '__main__':app = TransparentWindow(text_file='text.txt')app.mainloop()

效果

界面上鼠标点击右键可以选择“退出”:


鼠标移动到界面,会显示“锁定”和“解除锁定”按钮:

说明

        关于背景颜色、日期等等内容,大家可以修改相应的代码。

下载

https://xfxuezhang.lanzouo.com/b09ubrasb
密码:c9o1


http://www.ppmy.cn/news/953862.html

相关文章

太强大了!比ChatGPT更强大的桌面版本来了!

大家好&#xff0c;我是菜鸟哥&#xff01; 最近一边写Python代码&#xff0c;一边带着大家玩ChatGPT 。通过python可以挖掘GPT很多高级功能&#xff0c;通过GPT也可以更快学习Python。 目前我们社群已经有快600人了&#xff01;大家玩的不亦乐乎&#xff0c;一起玩微信机器人&…

ChatGPT的chrome插件无需apikey和服务器

简介&#xff1a; 安装教程 在chrome浏览器网址栏输入chrome://extensions/ 回车 然后点击右侧的开发者模式&#xff0c;再点击加载已解压的扩展程序 源码下载并解析到桌面&#xff0c;然后选择解析后的文件夹即可&#xff0c;然后点击选择文件夹不需要购买apikey也不需要服务…

【ChatGPT】桌面版有哪些?

今天OpenAI发布了ChatGPT的iOS版本&#xff0c;会不会出官方的桌面版呢&#xff1f;不管怎样&#xff0c;现在又开源的桌面版可用了&#xff0c;记录一下&#xff1a; ChatGPT&#xff0c;这是Rust版本的桌面版。 ChatBox 另外&#xff0c;如何写好提示&#xff0c;这里有一…

起步篇-- 超强的Chatgpt桌面版来了!可以保存聊天记录以及内置128个聊天场景!

Hello 小伙伴们,看了我们前面几篇起步篇的基本的内容,是不是已经开始玩起了ChatGPT了!但是有小伙伴不知道怎么聊天,因为Chatgpt有100多种prompt的角色,每一个场景都需要特殊的训练语句,才能完美的发挥ChatGPT的功能! 比如一些角色扮演啊,面试官啊,旅游啊,理财顾问啊,…

【无标题】chatgpt桌面化,桌面应用的安装

前言&#xff1a;关于chatgpt最近来说可算是大火&#xff0c;不过在我使用过程中发现没事都要上openai的官网过于麻烦&#xff0c;而且卡顿&#xff0c;于是乎就在网上寻找一些方法&#xff0c;发现chatgpt可以桌面化。 话不多说&#xff0c;直接上图。 1.上github找这位大佬 …

容器化时代的领航者:Docker 和 Kubernetes 云原生时代的黄金搭档

一、Docker docker是一种开源的应用容器引擎&#xff0c;可以将应用程序和依赖打包成一个可移植的镜像&#xff0c;然后发布到任何支持docker的平台上&#xff0c;也可以实现虚拟化。docker的核心概念有三个&#xff1a;镜像&#xff08;image&#xff09;、容器&#xff08;co…

【ArcGIS】shp导入报错ORA-00911无效字符

这个当个问题记录以下&#xff0c;就是shp文件名或者字段名有非正常字符&#xff0c;修改下名称重新导入即可&#xff1b; 直接改shp没法修改字段&#xff0c;会报错&#xff0c;需要先转化为gdb文件&#xff0c;然后在修改

php二分查找常用写法示列

二分查找常用写法有递归和非递归&#xff0c;在寻找中值的时候&#xff0c;可以用插值法代替求中值法。 当有序数组中的数据均匀递增时&#xff0c;采用插值方法可以将算法复杂度从中值法的lgN减小到lglgN /** * 二分查找递归解法 * param type $subject * param type $star…