LoginSignup
0
0

[python] urwidで表示内容を単位時間で更新する方法

Last updated at Posted at 2023-05-25

経緯

PythonでTUIアプリケーションを作る際に、urwidでメインループを開始後に一定時間経過する度に画面の表示内容を更新する処理を実装しようとして、一瞬詰まった+日本語の情報が殆どなかった ので備忘録代わりに投稿。

実装方法

RAMの使用率を毎秒更新して表示するプログラムを例に示す。

import urwid

def update(main_loop_obj,user_data):
    mem = psutil.virtual_memory() # get RAM infomation
    txt.set_text(f'{mem.percent}') # set new text to txt 
    loop.set_alarm_in(1,refresh) 

txt = urwid.Text('text', align='center')

fill = urwid.Filler(txt, 'top')
loop = urwid.MainLoop(fill)
loop.set_alarm_in(1,update) 
loop.run()

urwid.MainLoop.set_alarm_in()を用いる。

set_alarm_in( sec , callback , user_data=None )
 Schedule an alarm at tm time that will call callback from the within the run() function. Returns
 a handle that may be passed to remove_alarm().

Parameters:
tm (float) – time to call callback e.g. time.time() + 5
callback (callable) – function to call with two parameters: this main loop object and user_dataa

set_alarm_in()で指定秒数後にコールバック関数を呼び出すことが出来る。

loop.set_alarm_inで時間毎に処理したい関数を指定して呼び出し、その関数内で自分自身をまた指定して呼び出すことで、ループが続く限り指定秒数毎に関数が無限に実行される。
関数内で、urwid.Text.set_text()を用いてテキストの内容を更新している。

参考

0
0
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
0
0