Python - changing an external function without returning

I was just starting to learn Python, and I ran into this problem. I want to set a variable from inside the method, but the variable is outside the method.

The method is activated by the button. Then I want to get the value from this variable that I set when I press another button. The problem is that the value that I put inside the variable from the method does not remain. How can i solve this?

The code is below. currentMovieis the variable I'm trying to change. When I press a button using a method UpdateText(), it prints a random number, as expected. But when I press the button that activates UpdateWatched(), it outputs 0. So I assume that the variable will never be set.

import random
from tkinter import *

currentMovie = 0

def UpdateText():
    currentMovie = random.randint(0, 100)
    print(currentMovie)

def UpdateWatched():
    print(currentMovie)

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 = UpdateText)
button2 = Button(canvas, text = "GetRandomMovie", command = UpdateWatched)
button1.pack(anchor = NW, side = "left")
button2.pack(anchor = NW, side = "left")
root.mainloop()
+4
2

global :

def UpdateText():
    global currentMovie
    currentMovie = random.randint(0, 100)
    print(currentMovie)

global. .

+3

( python 2.x) , 1 , 2 () .

, , , . Tkinter, , - .

NB: python 3.x Tkinter Tkinter ( ), object Model.

import random
from Tkinter import *


class Model(object):
    def __init__(self):
        self.currentMovie = 0

    def UpdateCurrentMovie(self):
        self.currentMovie = random.randint(0, 100)
        print(self.currentMovie)

    def UpdateWatched(self):
        print(self.currentMovie)

    def ExampleWithArgs(self, arg):
        print("ExampleWithArg({})".format(arg))


def main():
    model = Model()
    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=model.UpdateCurrentMovie)
    button2 = Button(canvas, text = "GetRandomMovie", command=model.UpdateWatched)
    button3 = Button(canvas, text = "ExampleWithArg", command=lambda: model.ExampleWithArgs("foo"))
    button1.pack(anchor = NW, side = "left")
    button2.pack(anchor = NW, side = "left")
    button3.pack(anchor = NW, side = "left")
    root.mainloop()

if __name__ == "__main__":
    main()
+4

Source: https://habr.com/ru/post/1656706/


All Articles