Python variable stuck inside of my function

Viewed 65

The variable is stuck inside of the function because the code outside the function can't recongnize the variable(Number).

I make the random integer("Number") in the function("Roll_Dice") so when I call it with a button("b") it gets created and recreated.

I've tried to find the solution for this but all I could find was to use return function which makes sense but that doesn't work either, I prob used it wrong but tell me if I did please

And yes I am very aware that this is a very noob question but that's okay I hope right? :)

Here is the code, again I am a beginner at programming

import random
from tkinter import *

# here we assign the Tkinter window to a variable and give it a messure
window = Tk()
window.geometry("200x100")

#defining the function Roll_Dice generating the number from 1 to 6 at random
def Roll_Dice():
    Number = random.randint(1, 6)
    print(Number)
    return Number()

# now we make a button with a name
b = Button(window,text = "roll dice", activebackground = "pink",relief= GROOVE,command = Roll_Dice, pady = 15)
b.pack(side = RIGHT)

# here we make a label to show the result of the dice (for now in symbol, later in image)
l =Label(window, text = Number, pady = 5)
l.pack(side = LEFT)

window.mainloop()
2 Answers

Number variable is essentially lost after being "computed", because the code does nothing with it:

  • if Number isn't returned, it's cleaned up when function exits (read up on scopes, namespaces, local / global variables)
  • when Number is returned, there's nothing happening with it, because Tk ignores button callback return values

What you want to do is to write a function that "calculates" the random number and sets text label. That function (accepting no arguments and returning nothing) should be your callback.

You can create other function rand_num() to generate random number and return its value then call it in label text.

Also, modify Roll_Dice() function for updating label text when button pressed/clicked with rand_num() return value.

import random
from tkinter import *

# here we assign the Tkinter window to a variable and give it a messure
window = Tk()
window.geometry("200x100")

#defining the function Roll_Dice generating the number from 1 to 6 at random
def rand_num():
    number = random.randint(1, 6)
    return number

def Roll_Dice():
    l['text'] = rand_num()

# now we make a button with a name
b = Button(window,text = "roll dice", activebackground = "pink",relief= GROOVE,command = Roll_Dice, pady = 15)
b.pack(side = RIGHT)

# here we make a label to show the result of the dice (for now in symbol, later in image)
l =Label(window, text = rand_num(), pady = 5)
l.pack(side = LEFT)

window.mainloop()
Related