简体   繁体   English

如何从def永久更改全局变量

[英]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.我有一个名为 WEEK_ONE_REFINED 的全局变量。 I press a button and call change_it.我按下一个按钮并调用change_it。 I then press another button and call print_it but all it prints is the original "" value.然后我按下另一个按钮并调用 print_it 但它打印的只是原始的 "" 值。 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) change_it之前不叫print_it()可能是按钮不叫)
  • the strftime expression provides an empty string (unlikely) strftime表达式提供一个空字符串(不太可能)

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.我会说你的问题是week_one_refined.strftime("%d/%m/%Y")抛出异常,并且变量永远不会更新。

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.感谢你的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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