简体   繁体   中英

Alternative time.sleep() in Python

I was trying to make a game with Tkinter, but keeps crashing because of time.sleep() , because it makes the window sleep so it doesn't refresh.

I tried searching for "Tkinter window crashing from time.sleep" and only found 1 question with -9 votes.

Is there an alternative of time.sleep() ? I'm currently new to Python and stack overflow. If there is so, please answer.

and Thanks for helping me!

Preface: I am not familiar with Tkinter, but the following information will apply to all GUI applications, so I hope it's helpful.

The core of any GUI application is the main event loop . This is a continuous loop that gathers user input such as keyboard presses or mouse clicks, and then draws an image to the screen. If your program fails to process events quickly, Windows will show an error message like the following:

“X 没有响应”对话框的屏幕截图

This means your program can never sleep for more than a second or so. The solution is to rewrite the program to only sleep for very short time periods. Consider the following program:

reaction_time = 0
current_image = "screen1.jpg"
delay = get_random_number_of_milliseconds()

# Main event loop:
while True:
    key = get_keypress()

    if delay < 0:
        current_image = "screen2.jpg"
        if key == ENTER:
            print("Your reaction time was:", reaction_time)
            exit()
        else:
            reaction_time = reaction_time + 100
    else:
        delay = delay - 100

    draw_image_to_screen(current_image)
    sleep(0.1)

As you can see, this program decrements the value of delay each loop by 100 milliseconds, and then calls sleep(0.1) which will sleep for approximately 0.1 seconds.

Image that screen1.jpg contains a blank image and screen2.jpg contains a red circle. This program would first wait for a random time, then start incrementing the reaction_time variable as soon as the red circle is shown, and exit when the user presses Enter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM