LoginSignup
9
9

More than 3 years have passed since last update.

PySimpleGUIでの時刻表示(timeoutの使い方)

Posted at

はじめに

PySimpleGUIでTKのafter(一定時間ごとに繰り返し実行する。JavascriptではsetInterval)みたいなことはできないかと思ったところ、timeoutを使えばできるようでした。
そこで、TKの時刻表示のサンプルを書き換えてみました。

環境

Win10Pro
Anaconda
Python3.7
PySimpleGUIのインストールやもろもろは、以下を参照してください。
PySimpleGUIでQRコード作成GUIを作る

TKによるデジタル時計

お気楽 Python/Tkinter 入門
アナログ時計の項目の中のデジタル時計を参考にしています。

after() メソッド
今回はユーザからの入力がなくても時計を動かさないといけなので、単純なイベント駆動型アプリケーションでは「時計」を実現することはできません。
このため、プログラム自身でなんらかのきっかけを作ってやる必要があります。このような場合、役に立つメソッドが after() です。

from tkinter import *
# サンプルではTkinterとなっていますが、Python3では小文字のtkinterになります。
import time 

root = Tk()
root.option_add('*font', ('FixedSys', 14))

buff = StringVar()
buff.set('')

Label(textvariable = buff).pack()

# 時刻の表示
def show_time():
    buff.set(time.strftime('%I:%M:%S'))
    root.after(1000, show_time)
    #1000msの後にshow_time関数を呼び出しています。

show_time()
root.mainloop()

実行例
tk1.JPG

PySimpleGUIによるデジタル時計

cookbookのAsynchronous Window With Periodic Updateを参考に書いています。
cookbook Asynchronous Window With Periodic Update

import PySimpleGUI as sg
import time

def show_time():
    jikan = time.strftime('%I:%M:%S')
    return jikan

sg.theme('Dark')

layout= [[sg.Text(size=(8, 1), font=('Helvetica', 20),justification='center', key='-jikan-')]]

window = sg.Window('Watch',layout)

while True:
    event, values = window.read(timeout=100,timeout_key='-timeout-')
    #timeoutを指定することで、timeoutイベントが起こります。timeoutの単位はたぶんms
    # print(event,values)
    #↑コメントアウトを外すと、どんなイベントが起こっているか確かめることができます。

    if event in (None,):
        break
    elif event in '-timeout-':
        jikan = show_time()
        window['-jikan-'].update(jikan)

window.close()

実行例
psg1.JPG

まとめ

一定時間ごとに繰り返し実行する(tkのafter)ことが、timeoutを設定することで、実現できました。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9