Search code examples
pythontkinterdice

How can I get the outcome of the two dice to show as a result in a "scorebox" in python?


It's pretty simple, I wish to show the value of the two dice combined in a "scorebox" somewhere in the GUI. I have tried to look everywhere, but can't come up with a simple solution anywhere. Anyone able to help a python noob? :)

(The code is copied from a YouTube tutorial, so not my code.)

import tkinter as tk
import random

#creating the GUI itself
root = tk.Tk()
root.geometry('600x400')
root.title('Roll Dice')

label = tk.Label(root, text='', font=('Helvetica', 260))

#dice function
def roll_dice():

    dice = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685']
    label.configure(text=f'{random.choice(dice)} {random.choice(dice)}')
    label.pack()
    
#button to press to start rolling the dice
button = tk.Button(root, text='Roll Dice', foreground='black', command=roll_dice)
button.pack()

root.mainloop()

Solution

  • You can simply map the text inside a dictionary and then use indexing on the key to get the scores, and then just add the scores.

    dice = {'\u2680':1, '\u2681':2, '\u2682':3, '\u2683':4, '\u2684':5, '\u2685':6}
    scorebox = tk.Label(root, font=('Helvetica', 20)) # Make a scoresheet label
    
    def roll_dice():
        first,second = random.choice(list(dice)), random.choice(list(dice)) # Two random rolls
        score_text = dice[first] + dice[second] # Corresponding texts
    
        label.configure(text=f'{first} {second}') # Change the label
        scorebox.configure(text=score_text)
    
        label.pack()
        scorebox.pack()
    

    Why is the dictionary defined outside the function? So that it is just defined once and does not overwrite unnecessarily inside the function.