0

I need a code to make a button appear at a random time from [0-10] seconds. Currently my code looks like this:

#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)

It is the "button1" I need to make appear after 0-10 seconds.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • you can try [`pack_forget()`](http://stackoverflow.com/a/3819568/2276527). Also look at the comment below this answer – Alok Apr 30 '14 at 06:59
  • And for random number you can look [here](http://stackoverflow.com/a/3996930/2276527) – Alok Apr 30 '14 at 07:07

2 Answers2

2

You can use the after method to delay a function from being called. after takes the time in milliseconds to delay a function, then the function, then any optional arguments for the function. To make the ms amount random, use the random method randrange or randint. Here's an example:

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()
atlasologist
  • 3,824
  • 1
  • 21
  • 35
0

If you happen to have pygame, just make a while loop like so:

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

The loop will pause a second every time it loops until it reaches the random time 'y'

PS: random comes with Python, but you have to download Pygame appart

Dalex
  • 359
  • 2
  • 3
  • 12
  • How does this make any button appear ? Moreover, `sleep` is *prohibited* in GUI since it hangs the whole program. By the way, there is no need for an external library, standard [time.sleep](https://docs.python.org/2/library/time.html#time.sleep) do the job. – FabienAndre Apr 30 '14 at 23:42