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

Time:12-01

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 emerges 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?

CodePudding user response:

You could use a global variable:

from tkinter import *
import random

window=Tk()
window.geometry("400x400")

l1=Label(window)
l2=Label(window)

def roll():
    global dice
    dice=random.randint(1,6)
    l1.config(text=f'{dice}')
    l1.pack()

def last():
    l2.config(text=f'Last roll was {dice}')
    l2.pack()

b1=Button(window,text="Roll the Dice!",foreground='blue',command=roll)
b1.pack()

b2=Button(window,text="Get last roll",foreground='blue',command=last)
b2.pack()

window.mainloop()

NOTE: This requires you to push the "roll" button first. If you push the "last" button first, you get a NameError exception (which can be prevented by defining dice with an initial value in the global scope).

  • Related