I built a small app with GTK/Python 3 and it's working great so far. I'm very new to Python, so please forgive any poor syntax/formatting/logic in the provided code snippets.
On startup, main()
makes a call to two functions that live in a separate file called table.py
. These functions are responsible for creating the table column headers from a predetermined string array (create_column_headers()
), and another for creating the table row values from an API response (create_row_values
)
I'm looking for the best/correct way to update the table/data created in create_row_values
every x seconds so that the table UI will be updated with the latest API response values.
main.py
import gi
import table
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Crypto Widget")
table.create_column_headers(self)
table.create_row_values(self)
win = MainWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
table.py
import gi
import cmc_api
import const
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
def create_row_values(self):
for i, d in enumerate(cmc_api.get_data()['data']):
self.list_store.append([
f"{d['name']}",
f"{d['symbol']}",
"${:,.4f}".format(d['quote']['USD']['price']),
f"{round(d['quote']['USD']['percent_change_24h'], 2)}",
f"{round(d['quote']['USD']['percent_change_7d'], 2)}",
"${:,.2f}".format(d['quote']['USD']['market_cap']),
"${:,.2f}".format(d['quote']['USD']['volume_24h']),
"{:,.2f}".format(d['circulating_supply'])
])
def create_column_headers(self):
self.list_store = Gtk.ListStore(str, str, str, str, str, str, str, str)
tree_view = Gtk.TreeView(model=self.list_store)
[tree_view.append_column(Gtk.TreeViewColumn(c, Gtk.CellRendererText(), text=i))
for i, c in enumerate(const.column_headers)]
self.add(tree_view)
Reiterating the question: how can I get the table's row values to be updated every x seconds - thus updating the UI with the latest values from the result of the API call?
Please let me know if you have any suggestions or can point me in the right direction!
You can use API such as GLib.timeout_add_seconds()
.
In the provided callback, you can fetch the latest results and update the list store. As long as you end it with return True
, the callback will be called again after x seconds.