制作python/tkinter标签小部件更新?

Ste*_*oss 18 python tkinter

我正在努力获取python/tkinter标签小部件来更新其内容.根据今天的早期主题,我按照如何组合小部件的说明进行操作.但是,在运行时,标签小部件不会更改内容,而只是保留其原始内容.据我所知,从来没有调用decrement_widget().有任何想法吗?

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()
Run Code Online (Sandbox Code Playgroud)

Mar*_*off 27

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

有关此内容的更多信息,请参阅Tkinter Book:

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

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

v.set("New Text!")
Run Code Online (Sandbox Code Playgroud)

  • 注意:严格要求使用StringVar.您可以直接使用`configure`更新标签小部件:`l = Label(...); ...; l.configure(text ="new text")`具有少一个要管理的对象的好处. (4认同)

Fre*_*son 8

我认为你得到一个"在赋值前引用"错误,因为Python认为remaining是在本地范围内.

在Python 3中,你可以说nonlocal remaining.但是在Python 2中,我不相信有一种方法可以引用非本地的非全局范围.这对我有用:

remaining = 0

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

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

  remaining = secs

  def decrement_label ():
    global remaining
    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()
Run Code Online (Sandbox Code Playgroud)