如何在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
sysimport: Your original code was missing this, which would throw an error when trying to redirectstdout. - Dedicated repeat function: Instead of a one-off lambda,
print_hello_repeatedlyhandles counting and timing. Using a globalprint_countlets 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 usingtime.sleep()because sleep would freeze your GUI until the loop finishes—after()keeps the interface responsive. - Newlines for readability: Added
\nto the redirector so each "Hello" shows up on a new line in the textbox. - Reset count: After 5 prints, we reset
print_countto 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
相关产品推荐
相关产品推荐

