in this code there are two Random Number Generators. One in the first line, the other in the function btn_yes
.
Both RNG's work fine, the print(nb)
directly after the generator in the function btn_yes
displays a random number like it should.
However, when btn_press
is activated after btn_yes
was activated (like it should in the program), the value of nb
doesn't change, no matter how often i execute btn_yes
. btn_press
just uses the same number that was generated by the first RNG.
What am I missing?
nb = random.randrange(0, 11)
def btn_press():
guess = int(entry.get())
print(guess)
if guess < nb:
answ["text"] = "Higher!"
elif guess > nb:
answ["text"] = "Lower!"
elif guess == nb:
answ["text"] = "Correct!"
btn2["bg"] = "#FF6C6C"
btn3["bg"] = "#32FF00"
def btn_no():
window.destroy()
def btn_yes():
answ["text"] = "Next Round! Type in a new number!"
btn2["bg"] = "#464646"
btn3["bg"] = "#464646"
nb = random.randrange(0, 11)
entry.delete(0, tk.END)
print(nb)
CodePudding user response:
The problem here is that when you change a global variable inside a function, you need to put global <variablename>
as the first line in the function. Otherwise, Python assumes you meant to make a new variable with that name that is only in scope inside the function, and the global variable remains unchanged.
You can see this by print
ing nb
inside the function btn_yes()
; you should see that it has a different value each time (and not the same value as the global nb
).
In this case, if you put global nb
as the first line in btn_yes()
, it should have the desired effect.