【问题标题】:Tkinter's widget.configure inside a while loopTkinter 的 widget.configure 在 while 循环中
【发布时间】:2016-04-16 22:11:28
【问题描述】:

我需要根据完成的计算更改 Tkinter 标签的文本。我正在使用简单的label.configure(text="something new")。问题是我需要在 while 循环的每次迭代中都这样做。该过程只是等到循环完成,然后显示最后一个结果。我一直需要它们。

def new_frequency_1000times():
  k=1
  while k>1000:
   #steps to determine new frequency f
   freq_out.configure(text=str(f))
   k=k+1

master=Tk()
freq_out = Label(master)
freq_out.grid(row=0, column=1)
button_freq=Button(okno, command=new_frequency_1000times, text="Get new f")
button_freq.grid(row=0, column=0)

知道如何在循环中强制“评估”吗?

【问题讨论】:

  • 为什么不把配置放在你的while循环中呢?并且代码可能会更好地显示问题。
  • 我确实做到了。没错,代码马上就会出现。

标签: python python-2.7 tkinter


【解决方案1】:

您的问题是您有一个 while 循环在主偶数线程中运行。因此,它一直阻塞,直到 while 循环完成。使用afterthreading

这是一个小例子:

import tkinter as tk

def new_frequency_1000times(k=0):

    if k < 1000:
        freq_out.configure(text=str(k))
        #1000 ms = 1 seconds, adjust to taste.
        root.after(10, lambda: new_frequency_1000times(k+1))

root=tk.Tk()
freq_out = tk.Label(root)
freq_out.grid(row=0, column=1)
button_freq=tk.Button(root, command=new_frequency_1000times, text="Get new f")
button_freq.grid(row=0, column=0)
root.mainloop()

【讨论】:

    【解决方案2】:

    您需要处理窗口系统事件以使任何可见的事情发生。像这样在一个紧密的循环中做任何事情只会锁定你的 UI。相反,您需要使用 after 方法将更改安排为某个时间间隔,并允许事件循环处理必要的 UI 事件。

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      相关资源
      最近更新 更多