python - 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!
解决方案
尝试:
window.after(2000, lambda: display.config(text=randrange(SIDES) + 1))
而不是:
window.after(2000)
display["text"] = str(randrange(SIDES) + 1)
推荐阅读
- php-7 - 在 laravel 6 中测试表单时出现此错误
- selenium-webdriver - Selenium Webdriver Chrome V80 iframe 名称为空,即使 DOM 表示它们有名称
- assembly - 计算单个 IA32 指令的内存访问(包括页表)
- windows - 查找远程计算机上的 RAM 大小
- python - 内核在执行 papermill 时死亡
- python - 如何使用 python 从 Outlook 中提取电子邮件正文并将其解析为 pandas df?
- javascript - JavaScript更改textarea值时的角度调用函数
- python - 在 Django 中,如何知道按下了哪个按钮?
- java - 如何在android studio上切换软键盘
- c# - 如何自动调整 DataGridView 标头