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

在模拟病毒的Python代码中添加延迟的技术求助

Fixing Delay in Your Python "Virus Simulation" Program

Hey there! Let's sort out the delay logic for your fun simulation program. First, let's break down what's happening with your current code, then show you better approaches for adding delays that play nice with Pygame and Tkinter.

The Problem with time.sleep() in Your Current Loop

You're using time.sleep(0.1) inside your main Pygame loop right now, and while it does add a delay, it has a big downside: it freezes your entire program during the sleep period. That means Pygame can't process events like clicking the close window button until the sleep finishes, making your app feel unresponsive. Tkinter dialogs might also glitch or take longer to pop up because of this block.

Better Option: Use Pygame's Clock.tick()

Pygame has a built-in tool for controlling loop speed that's perfect for this scenario: pygame.time.Clock(). It regulates your loop to run at a fixed frame rate, which gives you consistent delays without blocking event handling. Here's how to implement it:

  1. Initialize the clock right after starting Pygame:

    pygame.init()
    clock = pygame.time.Clock()  # Add this line
    screen = pygame.display.set_mode((800, 300))
    # ... rest of your init code
    
  2. Replace your time.sleep(0.1) line with clock.tick(10) at the end of your main loop. tick(10) ensures your loop runs ~10 times per second (each frame takes ~0.1 seconds, matching your original sleep delay):

    while True:
        screen.fill((0, 0, 0))
        # ... event handling code ...
        warning = f"Процент удаления: {a}"
        label3 = font.render(warning, 1, (12, 140, 0, 1))
        a = a + 1
        
        if a >= 100:
            break
        
        screen.blit(label2, (50, 50))
        screen.blit(label3, (50, 100))
        pygame.display.update()
        
        clock.tick(10)  # Move delay control here
    

Why This Works Better

  • clock.tick() accounts for the time your code spends processing events and rendering, so it keeps your frame rate consistent even if some frames take a little longer to run.
  • It doesn't block event processing—your close window button, Tkinter dialogs, and other interactions will feel responsive.

If You Must Use time.sleep()

If you still want to use time.sleep() for specific parts (like the 0.5-second delay after quitting Pygame, which is fine in that context), make sure to only use it outside the main event loop or after you've processed all pending events. Never put it in the middle of the loop where it blocks event handling.

Full Modified Code

Here's your code with the recommended changes:

import pygame
from tkinter import *
from tkinter import messagebox
import time
import random

pygame.init()
clock = pygame.time.Clock()  # Initialize clock
screen = pygame.display.set_mode((800, 300))
pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")
Tk().wm_withdraw()
font = pygame.font.SysFont("Lucida Console", 35)
label2 = font.render("DELETING ALL PASSWORDS. . . . .", 1, (12, 140, 0, 1))
a = 0

while True:
    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            time.sleep(0.5)
            screen = pygame.display.set_mode((800, 300))
            pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")
            messagebox.showerror("ERROR!", " Вы попытались закрыть окно! Начинаю удаление файлов")
    
    warning = f"Процент удаления: {a}"
    label3 = font.render(warning, 1, (12, 140, 0, 1))
    a = a + 1
    
    if a >= 100:
        break
    
    screen.blit(label2, (50, 50))
    screen.blit(label3, (50, 100))
    pygame.display.update()
    
    clock.tick(10)  # Control frame rate here

This should give you the smooth, consistent delay you want while keeping your program responsive.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:02:51