Home > Mobile >  Python variable returns two different values
Python variable returns two different values

Time:08-22

I am currently trying to create a GUI using tkinter and am having issues when accessing a variable from two different functions in separate files

main.py contains:

from tkinter import *
from model import *
import train
import test

root = Tk()

root.title("Character Recognition Menu")
btnTrain = Button(root,text="Train",command=train.Train)
btnTest = Button(root,text="Test",command=test.Test)

lblIntro.pack()
btnTrain.pack()
btnTest.pack()

root.mainloop()

model.py contains:

modelTrained = False

train.py contains:

from model import *

def Train():
    global modelTrained
    modelTrained = True
    print(modelTrained)

test.py contains:

from model import *

def Test():
    print(modelTrained)

When I click the Test button, False is printed, so that is alright.

When I click the Train button, True is printed, which is meant to happen.

But When I click the Test button again, False is printed, which means that the modelTrained variable never actually changed

I looked at the IDs of the variable when accessed from the different functions, and they were different. Is there a reason this happens and is there any way to get around this issue?

CodePudding user response:

I guess the reason why is that you are importing module train but in fact it's named trainWindow.py.

CodePudding user response:

I believe it is due to the way modules are imported, thanks to one of the comments.

I've also noticed that changing modelTrained from a boolean to a list helped, and that could be because when importing or passing the variable it does so as reference instead of as value.

  • Related