0

Im trying to use global variables in order to declare them at the start of my code just like you would in C# however when ever i edit them in a function and i try call it in another function it throws an error saying that the variable is not declared?

This is where i declare the variables:

from tkinter import *
import os

global Name
global Wmain
global directory

global Username
global Password
global Code

This is where i change the the directory variable:

def NameGet():
    Name = NameEntry.get()
    directory = ('C:\\Users\\Bradley\\Desktop\\Log In system\\Members\\' + Name + '.txt')
    CheckFile(Name)

This is where i am getting the error:

def SignUpFinished():
    with open(directory, W) as F:
        F.write(Username)
        F.write(Password)
        F.write(Code)
        F.close()

Now i feel im either making a really novice mistake or something isnt working right with my code. any ideas?

bradley plater
  • 1,272
  • 2
  • 9
  • 16
  • Whatever variables you want to use in a function, you need to add `global var` at the start (where var is the var you want to change). Instead of using so many global variables, I would recommend using a class to manage different methods relating to the same task. – SneakyTurtle Jul 12 '17 at 19:38
  • In your example it seems that your globals are constants. If that is the case then it's probably best to stick them in their own file and then import them. If you need to change the values then you probably want to wrap those into a singleton class. – Dan Jul 12 '17 at 19:38
  • When i try put global in front because i am using it in a statement i assume it throws an error would someone be able to show me a basic class that i could use for structure as I've never dived into classes – bradley plater Jul 12 '17 at 19:48

1 Answers1

0

In order to use global variable you need to explicitly set it inside a method.

For example:

a=4
def func():
    global a
    print(a)

func()
ashukid
  • 353
  • 3
  • 18