通过简单的GUI库,实现了Python的小工具制作:
源码如下:
import PySimpleGUI as sg import webbrowser import threading import time path = r"./duola.ico" # 定义GUI布局 layout = [ [sg.Text("执行时间:")], [sg.InputText(size=(5, 1), key='HOUR'), sg.Text("时"), sg.InputText(size=(5, 1), key='MINUTE'), sg.Text("分"), sg.InputText(size=(5, 1), key='SECOND'), sg.Text("秒")], [sg.Text("")], [sg.Text("网址信息:")], [sg.InputText(size=(30, 1), key='URL')], [sg.Text("")], [sg.Text("距离任务执行还剩:"), sg.Text(size=(8, 1), key='TIMER')], [sg.Text("")], [sg.Button('开始'), sg.Button('取消'), sg.Button('退出'), sg.Button('清空')], ] # 全局变量,用于标记是否终止定时任务和存储定时任务线程 terminate_flag = False timer_thread = None # 创建GUI窗口 window = sg.Window('tomato', layout, finalize=True, resizable=True, grab_anywhere=True) # 修改图标 window.TKroot.iconbitmap(path) def openTip(): layout = [ [sg.Text('')], [sg.Text('=== 任务已完成 ===')], [sg.Text('')], ] # 创建弹出窗口并设置图标 window = sg.Window('任务进度', layout, icon=path) # 将path_to_icon.ico替换为你的图标文件的路径 # 事件循环 while True: event, values = window.read() if event == sg.WIN_CLOSED: break # 关闭弹出窗口 window.close() def open_url_at_time(url, hour, minute, second, timer_element): global terminate_flag # 获取当前时间 current_time = time.localtime() target_time = time.struct_time((current_time.tm_year, current_time.tm_mon, current_time.tm_mday, int(hour), int(minute), int(second), current_time.tm_wday, current_time.tm_yday, current_time.tm_isdst)) # 计算距离目标时间的秒数 time_difference = int(time.mktime(target_time) - time.mktime(current_time)) while time_difference > 0 and not terminate_flag: timer_element.update(f'{time_difference} 秒') time.sleep(1) time_difference -= 1 # 如果未被终止,打开默认浏览器访问网址 if not terminate_flag: webbrowser.open(url) # 创建弹出窗口 openTip() while True: event, values = window.read() if event == sg.WIN_CLOSED or event == '退出': break elif event == '开始': # 获取用户输入的任务执行时间和网址 hour = values['HOUR'] minute = values['MINUTE'] second = values['SECOND'] url = values['URL'] # 创建定时任务线程 timer_thread = threading.Thread(target=open_url_at_time, args=[url, hour, minute, second, window.FindElement('TIMER')]) timer_thread.start() elif event == '取消': # 终止当前正在执行的定时任务 terminate_flag = True window.FindElement('TIMER').update('任务已被终止') elif event == '清空': # 清空用户输入 window.FindElement('HOUR').update('') window.FindElement('MINUTE').update('') window.FindElement('SECOND').update('') window.FindElement('URL').update('') # 关闭定时任务线程(如果存在) if timer_thread and timer_thread.is_alive(): terminate_flag = True timer_thread.join() # 关闭GUI窗口 window.close()
通过 Python 实现定时打开链接的功能
于 2023-10-15 17:19:28 首次发布