简体   繁体   中英

How to permanently change a global variable from a def

I am having problems updating and calling the value of a global variable.

I have tried looking up similar posts and articles on the internet. Also localising a small test which seems to run alright...however in this part of my overall code it doesn't work.

WEEK_ONE_REFINED = ""

def change_it():
    global WEEK_ONE_REFINED
    WEEK_ONE_REFINED = week_one_refined.strftime("%d/%m/%Y")

def print_it():
    print (WEEK_ONE_REFINED)

I have a global variable called WEEK_ONE_REFINED. I press a button and call change_it. I then press another button and call print_it but all it prints is the original "" value. Not the updated value.

Any reason why it needs to be global? This would be better:

def change_it(week_str):
    return week_str.strftime("%d/%m/%Y")

def print_it(week):
    print (week)

week = change_it("1/2/2019")
print_it(week)

You code is correct. If you are printing the original empty value, one of two things happens

  • change_it is not called before print_it() (probably the button doesn't call it)
  • the strftime expression provides an empty string (unlikely)

At first glance your code seems correct. I would say that your problem is that week_one_refined.strftime("%d/%m/%Y") is throwing an exception, and the variable never gets updated.

Sorry guys and thanks for all your help.

The function was linked to a checkbox and would only work if the checkbox was clicked. Once I began clicking the checkboxes the variables updated.

I have now fixed it so that the global variables are updated regardless of whether the checkboxes have been activated.

Thanks for all your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM