python 我如何在tkinter文本小部件中连续填充文本?

6yjfywim  于 2023-06-28  发布在  Python
关注(0)|答案(2)|浏览(218)

我在循环中创建数字。在stdout,你可以观察进度,因为循环中有一个print语句。但我想在tkinter文本小部件中使进度可见。所以在每次打印时,我也将新数字复制到一个文本部件中。但在文本部件中,当循环停止时,数字首先显示。

import tkinter as tk
def count():
    number = 0
    while number<10000:
        number += 1
        print(number)
        text.insert(tk.END, number)
        text.see(tk.END)
root = tk.Tk()
text = tk.Text(root)
text.grid()
button = tk.Button(root, text="run", command=count)
button.grid()
root.mainloop()

我希望在文本小部件中看到数字的方式与它们在stdout中显示的方式类似。

pkmbmrz7

pkmbmrz71#

有很多方法可以做到这一点,其中之一就是这个。
您可以使用.after方法来执行此操作

import tkinter as tk

def count(number):
    print(number)
    text.insert(tk.END, number) # or text.insert(tk.END, str(number) + '\n') to put a newline after each number
    if number < 10000: # change 10000 to whatever you want
        # Schedule the next update after 1 millisecond
        root.after(1, count, number + 1)

root = tk.Tk()
text = tk.Text(root)
text.grid()

button = tk.Button(root, text="Run", command=lambda: count(0))
button.grid()

root.mainloop()

第二种方法是使用Threading

from threading import Thread
import tkinter as tk
def count():
    number = 0
    while number<10000:
        number += 1
        print(number)
        text.insert(tk.END, number) # text.insert(tk.END, str(number) + '\n') to add a newline after each number
        text.see(tk.END)

def supportFunction():
    t = Thread(target=count)
    t.start()
root = tk.Tk()
text = tk.Text(root)
text.grid()
button = tk.Button(root, text="run", command=supportFunction) # Calling supporter function
button.grid()
root.mainloop()
ru9i0ody

ru9i0ody2#

这应该可以实现您想要的功能-我已经将其设置为在新的一行上打印每个数字,并在计数完成后取消after循环

import tkinter as tk

def count():
    global number  # allow this function to modify the value of 'number'

    loop = root.after(10, count)
    if number < 10000:
        number += 1
        text.insert(tk.END, str(number) + '\n')
        text.see(tk.END)
    else:
        number = 0  # reset
        root.after_cancel(loop)

root = tk.Tk()
text = tk.Text(root)
text.grid()
button = tk.Button(root, text="run", command=count)
button.grid()
number = 0  # declare the starting value globally instead of inside 'count'
root.mainloop()

相关问题