I am working on a board game using Tkinter.
I've set up a button and a dice that displays a random number (from 1 - 6).
I would like to use that random number to also keep track of each player's position on the board.
How can I assign the random number to a variable and so I can use it outside of the function?
Currently, each time I click the button, the dice displays a new random number on the GUI and the number is printed to the terminal.
Thank you.
# Dice
list1 = ["\u2680", "\u2681", "\u2682", "\u2683", "\u2684", "\u2685"]
def dice_click():
rand = random.choice(list1)
Label(text=rand, font=('Helvetica 50')) .grid(row=6, column=15, rowspan=2, columnspan=2)
if rand == "\u2680":
print(1)
elif rand == "\u2681":
print(2)
elif rand == "\u2682":
print(3)
elif rand == "\u2683":
print(4)
elif rand == "\u2684":
print(5)
elif rand == "\u2685":
print(6)
dice_button = Button(root, text="Roll", command=dice_click) .grid(row=8, column=15)
CodePudding user response:
From my understanding of your code snippet - you need to use the random number outside this function, but after every time a new random number is generated using dice_click function.
There are 2 ways through which this can be achieved.
- Using a global variable that you assign the random value to.
`# Dice
global curr_random
list1 = ["\u2680", "\u2681", "\u2682", "\u2683", "\u2684", "\u2685"]
def dice_click():
global curr_random
rand = random.choice(list1)
Label(text=rand, font=('Helvetica 50')) .grid(row=6, column=15, rowspan=2, columnspan=2)
if rand == "\u2680":
print(1)
elif rand == "\u2681":
print(2)
elif rand == "\u2682":
print(3)
elif rand == "\u2683":
print(4)
elif rand == "\u2684":
print(5)
elif rand == "\u2685":
print(6)
curr_random = rand
dice_click()
# Use curr_random for something else.
- Returning the variable from the function
# Dice
list1 = ["\u2680", "\u2681", "\u2682", "\u2683", "\u2684", "\u2685"]
def dice_click():
rand = random.choice(list1)
Label(text=rand, font=('Helvetica 50')) .grid(row=6, column=15, rowspan=2, columnspan=2)
if rand == "\u2680":
print(1)
elif rand == "\u2681":
print(2)
elif rand == "\u2682":
print(3)
elif rand == "\u2683":
print(4)
elif rand == "\u2684":
print(5)
elif rand == "\u2685":
print(6)
return rand
curr_random = dice_click()
# Use curr_random for something else.
You can use whichever you like according to your use case and the structure of the rest of the code.
CodePudding user response:
This is a 'scope issue', meaning that Python is doing as intended. When your variable is within a function, it is by default unreachable outside the function.
You could define it as a global
, or move the random function outside the scope. Simply appending global
in front of the variable will make it accessible from any scope. However, in your case, I'd recommend you define the random variable outside the function.