2014-04-30 28 views
1

我需要一個代碼來使按鈕在[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秒後出現。

+0

你可以試試['pack_forget()'](http://stackoverflow.com/a/3819568/2276527)。也請看下面這個回答下面的評論 – Gogo

+0

而對於隨機數,你可以看看[這裏](http://stackoverflow.com/a/3996930/2276527) – Gogo

回答

0

如果你碰巧有pygame的,只是做一個while循環,如下所示:

import pygame, random 
y = random.randrange(0, 10, 1) 
x = 0 
while x != y: 
    x += 1 
    pygame.time.wait(1000) 

循環將直到它到達任意時間「Y」

每次循環時間停頓一秒PS:隨機附帶Python,但您必須下載Pygame appart

+0

這是如何讓任何按鈕出現?而且,由於GUI掛起了整個程序,所以在GUI中禁止* sleep。順便說一下,不需要外部庫,標準的[time.sleep](https://docs.python.org/2/library/time.html#time.sleep)可以完成這項工作。 – FabienAndre

2

您可以使用after方法來延遲被調用的函數。 after以毫秒爲單位延遲一個函數,然後是該函數,然後是該函數的任何可選參數。要隨機使用ms數量,請使用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() 
相關問題