Search code examples
pythonbuttontkinterdice

Python random number generator not working properly


outcomeG = "0"
outcomeB = "0"

def roll(outcomeG, outcomeB):

    outcomeG = random.randint(1, 6)
    outcomeB = random.randint(1, 5)
    return outcomeG, outcomeB

def goodDiceRoll():

    goodDiceOptions.destroy()

    global goodDiceRoll
    goodDiceRoll = tkinter.Tk()
    goodDiceRoll.title("Green Dice roll")

    lbloutcome = tkinter.Label(goodDiceRoll, text="Press roll")
    btnRollG = tkinter.Button(goodDiceRoll, text="Roll", command=roll(outcomeG, outcomeB))

    if outcomeG == "1":
        lbloutcome.config(text="Green 1")
        goodDiceRoll.update()
        f = open("Logs.txt", "a")
        ts = time.time()
        sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
        f.write(sttime + "Green 1")
        f.close()

    elif outcomeG == "2":
        lbloutcome.config(text="Green 2")
        goodDiceRoll.update()
        f = open("Logs.txt", "a")
        ts = time.time()
        sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
        f.write(sttime + "Green 2")
        f.close()
        #rest of code

This is some of my code that is suppose to let you roll a green dice or red dice and then put it in a file. However when I press the roll button that i made, it is suppose to randomize a number from 1 to 6 and display it but what really happens is absolutely nothing. How can i fix this? Any help will be much appreciated.


Solution

  • If you do roll(outcomeG, outcomeB) then don't expect those two global variables to change. They will remain 0. This is because the (parameter) variables within roll are local to that function. Any assignment made to those variables will not affect the variables that were passed to the function.

    If you then call goodDiceRoll() the if blocks will not be entered since the values of those variables are still 0, and by consequence nothing gets written to the file.

    You can solve this by doing:

    outcomeG, outcomeB = roll()
    

    ... and remove the parameters from the roll definition.

    But, as you don't call roll that way, but pass a reference to it via:

    btnRollG = tkinter.Button(goodDiceRoll, text="Roll", command=roll)
    

    ... you are forced into using global variables. So modify roll like this:

    def roll():
        global outcomeG, outcomeB  
        outcomeG = random.randint(1, 6)
        outcomeB = random.randint(1, 5)
    

    Make sure to also define them as such in goodDiceRoll.

    Secondly, it is a really bad idea to assign to goodDiceRoll, which really destroys the previous value it had, i.e. the function you are in. This will make the function unreachable after the first invocation. Use a different variable name.