Mazze
Mazze

Reputation: 453

Rolling two dice vía Buttons

I am trying to create two dice, which can be rolled together or if marked as keep are rolled separately. I tried the following code. The roll_dice button rolls the dice. With botton1 and botton2 each die can be marked as keep, so there are not rolled if roll_dice is pressed.

import tkinter
import random

# toplevel widget of Tk which represents mostly the main window of an application
root = tkinter.Tk()
root.geometry('1200x600')
root.title('Roll Dice')

# label to display dice
label = tkinter.Label(root, text='', font=('Helvetica', 260))

# function activated by button
def switch1():
    button1["state"] = "disabled"
    
def switch2():
    button2["state"] = "disabled"

def roll_dice(var1, var2):
    # unicode character strings for dice
    dice = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685']

    
    if button1["state"] == "active" and button2["state"] == "active":
        var1 = f'{random.choice(dice)}'
        var2 = f'{random.choice(dice)}'
        label.configure(text= var1 + var2)
        label.pack()
    elif button1["state"] == "active":
        var2 = f'{random.choice(dice)}'
        label.configure(text= var1+var2)
        label.pack()
    elif button2["state"] == "active":
        var1 = f'{random.choice(dice)}'
        label.configure(text= var1 + var2)
        label.pack()

    
# button
dice = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685']
var1, var2 = [f'{random.choice(dice)}', f'{random.choice(dice)}']


button1 = tkinter.Button(root, text='keep', foreground='green', command=switch1, state = "active")
button2 = tkinter.Button(root, text='keep', foreground='green', command=switch2, state = "active")
button_roll = tkinter.Button(root, text='roll dice', foreground='green', command=lambda: roll_dice(var1, var2))
   
# pack a widget in the parent widget
button_roll.pack()
button1.pack()
button2.pack()

# call the mainloop of Tk
# keeps window open
root.mainloop()

When I run the code, the die marked as keep is rolled exactly one more time. After that, the die does not change when I roll it. How do I make it so that it is no longer rolled once?

Upvotes: 0

Views: 134

Answers (1)

SuperStormer
SuperStormer

Reputation: 5407

command=roll_dice(var1, var2)) is wrong, as you're calling the function instead of passing it as the callback. Either use a lambda, like command=lambda: roll_dice(var1, var2), or define a separate function for the callback.

Upvotes: 2

Related Questions