如何 "print" 在 Tkinter 中控制台登录?

How to "print" console logs in Tkinter?

我读了一些类似的问题,但我认为他们没有回答我的问题。

我有一个在 GUI 中单击按钮“运行”后数到 10 的基本代码:

from tkinter import *
from time import sleep

def count_to_10():
    for i in range(1,11):
        sleep(0.5)
        print(i)
        counter_label.after(0, counter_label.config(text=i))
    return

def GUI():
    root = Tk()

    run_button = Button(root, text="run", command=count_to_10)
    run_button.pack()

    global counter_label
    counter_label = Label(root, text="counter")
    counter_label.pack()

    root.mainloop()

GUI()

我希望 counter_label 文本在 count_to_10 函数的每次迭代后从 1 变为 10。 当函数 returns、not 而 运行s.

时,标签会发生变化

控制台输出:

1
2
3
4
5
6
7
8
9
10

标签变化:

The label only changes once to 10 after the end of the function.

同样的结果也适用于其他小部件,例如 scrolledtext, Text, 等。

如何在函数 运行s 时更改标签(或任何与文本相关的小部件)?

感谢您的帮助!

PS:有点像在GUI上有控制台输出。

你用错了after()。也不要在 tkinter 应用程序中使用 time.sleep(),因为它会阻止 tkinter mainloop 更新小部件。

更改count_to_10()如下:

def count_to_10(n=1):
    counter_label.config(text=n)
    if n < 10:
        counter_label.after(500, count_to_10, n+1)

您不需要使用 x.after() 方法。只需使用 configconfigure 方法。像这样:counter_label.configure(text=i) 然后你应该让 root 更新主 window 这条线:root.update()(root 应该是全局的或作为参数传递)。

完整代码:

from tkinter import *
from time import sleep


def count_to_10():
    for i in range(1, 11):
        sleep(0.5)
        print(i)
        counter_label.configure(text=i)  # Update the text in "Label" widget.
        root.update()  # Let root update the main window.


def GUI():
    global root
    root = Tk()

    run_button = Button(root, text="run", command=count_to_10)
    run_button.pack()

    global counter_label
    counter_label = Label(root, text="counter")
    counter_label.pack()

    root.mainloop()


GUI()

界面:

控制台输出:

>>> python3 test.py 
1
2
3
4
5
6
7
8
9
10

注:

您的标签仅更改过一次(当计数器为 10 时),因为 root 无法更新并且在您的 count_to_10 函数返回时(在 for 循环)当然最后一个数字是 10.