使 python/tkinter 标签小部件更新? [英] Making python/tkinter label widget update?

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

问题描述

我正在努力获取一个 python/tkinter 标签小部件来更新其内容.根据今天早些时候的一个线程,我按照有关如何组合小部件的说明进行操作.然而,在运行时,标签小部件不会更改内容,而只是保留其原始内容.据我所知,decrement_widget() 从来没有被调用过.有什么想法吗?

I'm working on getting a python/tkinter label widget to update its contents. Per an earlier thread today, I followed instructions on how to put together the widgets. At runtime, however, the label widget does NOT change contents, but simply retains its original content. As far as I can tell, decrement_widget() is never called at all. Any ideas?

def snooze (secs):
  """
  Snoozes for the given number of seconds. During the snooze, a progress
  dialog is launched notifying the 
  """

  root = Tkinter.Tk()
  prompt = 'hello'
  label1 = Tkinter.Label(root, text=prompt, width=len(prompt))
  label1.pack()

  remaining = secs

  def decrement_label ():
    text = "Snoozing %d sec(s)" % remaining
    remaining -= 1
    label1.config(text=text, width=100)
    label1.update_idletasks()

  for i in range(1, secs + 1):
    root.after(i * 1000, decrement_label )

  root.after((i+1) * 1000, lambda : root.destroy())
  root.mainloop()

推荐答案

您需要使用 StringVar;当 StringVar 更改时(通过调用 myStringVar.set("text here")),标签的文本也会更新.是的,我同意,这是一种奇怪的做事方式.

You'll want to set the label's textvariable with a StringVar; when the StringVar changes (by you calling myStringVar.set("text here")), then the label's text also gets updated. And yes, I agree, this is a strange way to do things.

请参阅 Tkinter Book 了解更多信息:

See the Tkinter Book for a little more information on this:

您可以将 Tkinter 变量与标签相关联.当变量的内容发生变化时,标签会自动更新:

You can associate a Tkinter variable with a label. When the contents of the variable changes, the label is automatically updated:

v = StringVar()
Label(master, textvariable=v).pack()

v.set("New Text!")

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

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