You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tkinter/GUI中重复打印同一文本5次?

Solution: Repeat Text Printing 5 Times with Timer in Tkinter

Got it, let's get your button to print "Hello" 5 times with a timer (so it doesn't all pop up at once—plus we'll make sure the GUI stays responsive). Here's the adjusted code, along with a breakdown of what's changed:

import sys
from tkinter import *

root = Tk()
textbox = Text(root)
textbox.pack()

# Track how many times we've printed (reset after each button click)
print_count = 0

def redirector(inputStr):
    textbox.insert(INSERT, inputStr + "\n")  # Add newline for readability
    sys.stdout.write = redirector

def print_hello_repeatedly():
    global print_count
    print_count += 1
    print("Hello")  # This gets redirected to the textbox
    
    if print_count < 5:
        # Call this function again after 1 second (1000ms)
        root.after(1000, print_hello_repeatedly)
    else:
        # Reset count so we can click the button again later
        print_count = 0

button1 = Button(root, text='Output Name', command=print_hello_repeatedly)
button1.pack()

sys.stdout.write = redirector
root.mainloop()

Key Changes & Explanations:

  • Added sys import: Your original code was missing this, which would throw an error when trying to redirect stdout.
  • Dedicated repeat function: Instead of a one-off lambda, print_hello_repeatedly handles counting and timing. Using a global print_count lets us track how many times we've printed across function calls.
  • Timer with after(): root.after(1000, ...) tells Tkinter to run the function again after 1 second. This is way better than using time.sleep() because sleep would freeze your GUI until the loop finishes—after() keeps the interface responsive.
  • Newlines for readability: Added \n to the redirector so each "Hello" shows up on a new line in the textbox.
  • Reset count: After 5 prints, we reset print_count to 0 so you can click the button again to run the sequence over.

If you don't want a delay between prints (just instant 5x output), you can simplify the function to a loop instead:

def print_hello_five_times():
    for _ in range(5):
        print("Hello\n")  # Newline here to separate entries

Then set command=print_hello_five_times on the button. But the timer version is probably what you're looking for since you mentioned a timer!

内容的提问来源于stack exchange,提问作者Brendo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:25:35