directedition
directedition

Reputation: 11705

Updating tkinter labels in python

I'm working on giving a python server a GUI with tkinter by passing the Server's root instance to the Tkinter window. The problem is in keeping information in the labels up to date.

For instance, the server has a Users list, containing the users that are logged on. It's simple enough to do this for an initial list:

string = ""
for user in self.server.Users:
  string += user + "\n"

Label(master, text=string)

But that will only do it once. After that, how am I supposed to update the list? I could add an 'update users' button, but I need the list to be self-updating.

Upvotes: 2

Views: 7417

Answers (2)

Strider1066
Strider1066

Reputation: 101

You change the text of a Label by setting the text of its corresponding StringVar object, for example:

from tkinter import *

root = Tk()
string = StringVar()
lab = Label(root, textvariable=string)
lab.pack()
string.set('Changing the text displayed in the Label')
root.mainloop()

Note the use of the set function to change the displayed text of the Label lab.

See New Mexico Tech Tkinter reference about this topic for more information.

Upvotes: 2

Markus Jarderot
Markus Jarderot

Reputation: 89171

You could use callbacks on the server instance. Install a callback that updates the label whenever the user-list changes.

If you can't change the server code, you would need to poll the list for updates every few seconds. You could use the Tkinter event system to keep track of the updates.

def user_updater(self):
    self.user_updater_id = self.user_label.after(1000, self.user_updater)
    lines = []
    for user in self.server.Users:
        lines.append(user)
    self.user_label["text"] = "\n".join(lines)

def stop_user_updater(self):
    self.user_label.after_cancel(self.user_updater_id)

Upvotes: 3

Related Questions