mardi 30 novembre 2021

Python: Getting variable from a function that generates random numbers by pressing a button

I'm working on a game where you have to roll the dice. When I press the button, a random value from 1 to 6 emarges and is printed in the window - that's fine. The problem is that I need to somehow get the same value as the one that the 'dice' showed. Here is my code:

from tkinter import *
import random
 
window=Tk()
window.geometry("400x400")
 
l1=Label(window)
 
def roll():
    dice=random.randint(1,6)
    l1.config(text=f'{dice}')
    l1.pack()
     
b1=Button(window,text="Roll the Dice!",foreground='blue',command=roll)
b1.pack()
 
window.mainloop()

Here I want to get the value dice and use this value somewhere else but the function roll is bound to the command of the button b1. I tried to create another function and even a class but then I run into other problems such as that the number on the dice won't change even after I press the button repeatedly etc. Now I've run out of ideas. Could you edit my code so that the program works just as before but it also returns the value that the dice showed so that I can use the same value somewhere else?




Aucun commentaire:

Enregistrer un commentaire