在 python 中更新 tkinter 标签 [英] Updating tkinter labels in python

查看:45
本文介绍了在 python 中更新 tkinter 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过将服务器的根实例传递给 Tkinter 窗口,为 python 服务器提供带有 tkinter 的 GUI.问题在于保持标签中的信息是最新的.

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.

推荐答案

您可以在服务器实例上使用回调.安装一个回调,在用户列表发生变化时更新标签.

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

如果您无法更改服务器代码,则需要每隔几秒轮询一次列表以获取更新.您可以使用 Tkinter 事件系统来跟踪更新.

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)

这篇关于在 python 中更新 tkinter 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆