0

Here is an example of a random spin button using a button surrounded by labels to create the feeling of a spin animation. This example uses the Tkinter GUI and lets you select numbers 1 to 6. If your game requires more then this, just add additional labels. You are encouraged to experiment with this code and maybe locate the labels in a more circular fashion around the button.

# create a button surrounded by labels to mimic a random spin button
# tested with Python24         vegaseat        23dec2006

import Tkinter as tk  # use tk namespace for Tkinter items
import random

def make_labels():
    """
    create a list of labels and position them
    """
    labels = []
    for k in range(1, 7):
        labels.append(tk.Label(root, text=' %d ' % k, bg='yellow'))
    # now assign a grid position to each label
    for  ix, label in enumerate(labels):
        if ix < 3:
            label.grid(row=0, column=ix, pady=5)
        elif ix == 3:
            button1 = tk.Button(root, text='Press me', command=click)
            button1.grid(row=1, column=0, columnspan=3)
            label.grid(row=2, column=2, pady=5)
        else:
            label.grid(row=2, column=5-ix, pady=5)
    return labels

def click():
    """
    loop/spin through the labels and pick one to stop at random
    """
    # reset all labels to same color
    for label in labels:
        label.config(bg='yellow')
    # start with a time delay of 15 ms and increase it in the spins
    t = 15
    stop = random.randint(19, 24)
    for x in range(0, stop):
        label = labels[x%6]
        root.after(t, label.config(bg='green'))
        root.update()
        root.title(str(x%6 + 1))  # test
        if x == stop-1:
            # final result available via var1.get()
            var1.set(str(x%6 + 1))
            break
        root.after(t, label.config(bg='yellow'))
        t += 15

# create the window form
root = tk.Tk()

# StringVar() updates result label automatically
var1 = tk.StringVar()
# set initial value
var1.set("")
# create the result label
result = tk.Label(root, textvariable=var1, fg='red')
result.grid(row=3, column=0, columnspan=3)

# create the list of labels
labels = make_labels()

# start of program event loop
root.mainloop()
2
Contributors
1
Reply
4
Views
10 Years
Discussion Span
Last Post by Bill Fisher
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.