在一段时间后显示按钮
我需要一段代码,让一个按钮在0到10秒之间的随机时间出现。目前我的代码是这样的:
#Importere værktøjer
from tkinter import*
import datetime
import time
import os
import datetime
import random
#Tiden
start = time.clock()
t = datetime.datetime.now()
#Definitioner
def myClickMe1():
finish = time.clock()
elapsed_time = finish - start
label1["text"]='{0:.2f}'.format(elapsed_time)
print('{0:.2f}'.format(elapsed_time))
return
#rod defineres
window=Tk()
#Vinduet
window.geometry("700x800")
window.title("Reaktionshastighehs test")
#Labels
label1=Label(window, text="Klik nu!")
#indstillinger til objekter
button1=Button(window, text="Klik her!", command=myClickMe1)
#Placering af objekter
button1.place(x=330, y=460)
label1.place(x=335,y=500)
我想让这个“button1”在0到10秒后出现。
2 个回答
0
如果你有安装pygame的话,可以像这样写一个循环:
import pygame, random
y = random.randrange( 0, 10, 1)
x = 0
while x != y:
x += 1
pygame.time.wait(1000)
这个循环每次运行的时候都会暂停一秒,直到它达到一个随机的时间'y'。
补充说明:random是Python自带的功能,但你需要单独下载Pygame。
2
你可以使用 after
方法来延迟调用一个函数。这个 after
方法需要你指定延迟的时间,单位是毫秒,然后是你想要调用的函数,最后可以加上一些可选的参数。如果你想让延迟的时间随机,可以使用 random
模块里的 randrange 或者 randint 方法。下面是一个例子:
from tkinter import *
import random
root = Tk()
btn = Button(root, text='Button')
random_time = random.randint(0, 5000) # get a random millisecond amount between 0-5 secs
root.after(random_time, btn.pack) # call the after method to pack btn after random_time
mainloop()