I just started learning Python and I ran into this problem. I want to set a variable from inside a function, but the variable is outside the function.
The function gets activated by a button. Then I want to get the value from that variable that I set when I press another button. The problem is that the value that I put inside a variable from inside the function doesn't stay. How would I solve this?
The code is underneath. currentMovie
is the variable I try to change. When I press the button with the function update_text()
, it prints out a random number like it is supposed to. But when I press the button that activates update_watched()
it prints out 0. So I am assuming the variable never gets set.
import random
from tkinter import *
current_movie = 0
def update_text():
current_movie = random.randint(0, 100)
print(current_movie)
def update_watched():
print(current_movie)
root = Tk()
root.title("MovieSelector9000")
root.geometry("900x600")
app = Frame(root)
app.grid()
canvas = Canvas(app, width = 300, height = 75)
canvas.pack(side = "left")
button1 = Button(canvas, text = "SetRandomMovie", command = update_text)
button2 = Button(canvas, text = "GetRandomMovie", command = update_watched)
button1.pack(anchor = NW, side = "left")
button2.pack(anchor = NW, side = "left")
root.mainloop()