如何修改Spambot代码的running布尔值实现按钮启停?解决界面冻结问题
Fixing Your Spambot's UI Freeze and Start/Stop Issues
Hey there! Let's break down why your spambot is misbehaving and get it working smoothly again. You've got two core issues here—let's work through them step by step:
What's Going Wrong?
- Stop Button Doesn't Trigger the Function: You named your stop button
stop, which overwrites thestop()function you defined earlier. So when you click the button, it's not actually calling your code to setrunning = False. - UI Freezes After Input: Your
while Trueloop is hogging the main thread non-stop, blocking Tkinter's event loop from handling UI updates (like typing in the input box or processing button clicks). The occasionalroot.update()isn't enough to keep the interface responsive.
Fixed Code
Here's the revised version that fixes both problems, using Tkinter's built-in after() method to run the spamming loop without blocking the UI:
from tkinter import * from pynput.keyboard import Key, Controller import time keyboard = Controller() running = False # Start with spamming disabled idx = 0 def start(): global running running = True # Kick off the spam loop only if it's not already running if running: spam_loop() def stop(): global running running = False def spam_loop(): global idx if running: text = var.get() if text: # Only spam if there's text in the input box for char in text: keyboard.press(char) keyboard.release(char) time.sleep(0.1) # Shortened for testing—adjust back to 1s if needed idx += 1 # Schedule the next loop run after 100ms (tweak this interval as desired) root.after(100, spam_loop) root = Tk() var = StringVar() root.geometry("500x300") root.title("Spambot") write = Label(text="Insert sentence then print the button:") # Rename the button to avoid overwriting the stop() function stop_button = Button(text="Stop", command=stop) spam_button = Button(text="Spam", command=start) enter = Entry(root, textvariable=var) write.pack() enter.pack() spam_button.pack() stop_button.pack() root.mainloop()
Key Improvements:
- Fixed Stop Button Naming: The button is now
stop_buttoninstead ofstop, so it no longer overwrites yourstop()function. - Replaced
while Truewithafter(): Thespam_loop()usesroot.after()to schedule itself repeatedly, which lets Tkinter handle UI events between loop runs—no more frozen interface. - Added Input Check: The bot only runs if there's text in the input box, so it won't waste cycles on empty entries.
- Adjusted Sleep Timing: Shortened the delay between characters for quicker testing; you can set it back to 1 second if you need slower spamming.
This should resolve both the UI freeze and the unresponsive start/stop buttons. Give it a test run!
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

