代码:
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
表示移除标题栏。