首页 > 解决方案 > How to add a delay between 2 text messages being displayed in Tkinter Python?

问题描述

So my aim is to use a single function to show a text message upon a button click. Then there should be a delay and then another text message should be displayed.

The game is a dice game that should show 'Rolling...' upon a button click. And then after a while, it should display a random number.

I tried both .sleep() and .after() and both of them resulted in my program not showing the before delay text. Here's my code:

# Imports
import tkinter as tk
from random import randrange
import time

# Global variables
# SIDES is a constant
SIDES = 12

# Functions
def func():
    display["text"] = "Rolling..."
    window.after(2000)
    display["text"] = str(randrange(SIDES) + 1)
    

# Main program loop
window = tk.Tk()

display = tk.Label(window, text="Press the button \nto roll the dice.", width=20, height=3)
button = tk.Button(window, text="Roll", command=func)

display.pack()
button.pack(pady=10)

window.mainloop()

Any help would be much appreciated!

标签: pythonfunctiontkintersleep

解决方案


尝试:

window.after(2000, lambda: display.config(text=randrange(SIDES) + 1))

而不是:

window.after(2000)
display["text"] = str(randrange(SIDES) + 1)

推荐阅读