Skip to content Skip to sidebar Skip to footer

Update A Label In Gtk, Python

I am learning GTK at the moment. Feels like i am loosing my time with the documentation. And tutorials are pretty thin. I am trying to make a simple app that can display my CPU's

Solution 1:

You should call all your methods via a timeout:

GLib.timeout_add(ms, method, [arg])

or

GLib.timeout_add_seconds(s, method, [arg])

where ms are milliseconds and s are seconds (update interval) and method would be you getUsage and getTemp methods. You can pass the labels as arg.

Then you just have to call the set_text(txt) method on the label(s)

Note: You need to import GLib like this:

from gi.repositoryimport GLib

EDIT #1

As @jku pointed out, the following methods are outdated and maybe just exist to provide backward compatability with legacy code (so you should not use them):


GObject.timeout_add(ms,method,  [arg])

or

GObject.timeout_add_seconds(s,method,  [arg])

EDIT #2

As your data methods get_temp and get_usage are more universal, you can use a little wraper function:

def updateLabels(labels):
    cpuLabel  = labels[0]
    tempLabel = labels[1]
    cpuLabel.set_text(CpuData.get_usage())
    tempLabel.set_text(CpuData.get_usage())
    return False

Then simply do:

GLib.timeout_add_seconds(1, updateLabels, [cpuLabel, tempLabel]) # Will updateboth labels once a second

EDIT #3

As I said, here is the example code:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GLib
import time


classTimeLabel(Gtk.Label):
    def__init__(self):
        Gtk.Label.__init__(self, "")
        GLib.timeout_add_seconds(1, self.updateTime)
        self.updateTime()


    defupdateTime(self):
        timeStr = self.getTime()
        self.set_text(timeStr)
        return GLib.SOURCE_CONTINUE

    defgetTime(self):
        return time.strftime("%c")


window = Gtk.Window()
window.set_border_width(15)
window.connect("destroy", Gtk.main_quit)

window.add(TimeLabel())
window.show_all()
Gtk.main()

Post a Comment for "Update A Label In Gtk, Python"