2.4 PySimpleGUI 创建一个桌面计时器

代码:

import PySimpleGUI as sg
import time

def time_as_int():
    '''初始化计时'''
    return int(round(time.time() * 100))

# ----------------  Create Form  ----------------
sg.ChangeLookAndFeel('Black')
sg.SetOptions(element_padding=(0, 0))

layout = [[sg.Text('')],
         [sg.Text(size=(8, 2), font=('Helvetica', 20), justification='center', key='display')],
         [sg.ReadButton('Pause', key='Pause', button_color=('white', '#001480')),
          sg.ReadButton('Reset', button_color=('white', '#007339'), key='Reset'),
          sg.Exit(button_color=('white', 'firebrick4'), key='Exit')]]

window = sg.Window('Running Timer', layout, no_titlebar=True, 
         auto_size_buttons=False, keep_on_top=True, grab_anywhere=True)

# ----------------  main loop  ----------------
current_time, paused_time, paused = 0, 0, False
start_time = time_as_int()
while 1:
    # --------- Read and update window --------
    if not paused:
        event, values = window.read(timeout=10) # run every 10 milliseconds
        current_time = time_as_int() - start_time
    else:
        event, values = window.read()
    # --------- Do Button Operations --------
    if event in (None, 'Exit'):        # ALWAYS give a way out of program
        break
    elif event == 'Reset':
        paused_time = start_time = time_as_int()
        current_time = 0
    elif event == 'Pause':
        paused = not paused
        if paused:
            paused_time = time_as_int()
        else:
            start_time = start_time + time_as_int() - paused_time
        window['Pause'].update('Run' if paused else 'Pause')      # Change button's text

    # --------- Display timer in window --------
    window['display'].update('{:02d}:{:02d}.{:02d}'.format((current_time // 100) // 60,
                                                                  (current_time // 100) % 60,
                                                                  current_time % 100))
window.close()

效果图:

一个计时器

其中 sg.Window 的参数 no_titlebar=True 表示移除标题栏

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容