微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在这段代码中实现一个全局变量,以便可以在其他函数中使用?使用 Tkinter 和 Python 3

如何解决如何在这段代码中实现一个全局变量,以便可以在其他函数中使用?使用 Tkinter 和 Python 3

我将如何为 get_credit_score 中的所有变量实现一个全局变量,以便它们可以在advice_to_be_given 中读取。

def close_window(self):
    self.master.destroy()

def get_credit_score(self):
    monthlyWage = int(input("What is your monthly wage? "))
    monthlySpendings = int(input("What are your monthly spendings? ")) 
    monthlyOverdraft = int(input("What is your monthly overdraft? "))
    monthlySavings = int(input("How much do you add into your savings account per month? "))

def advice_to_be_given(self):
    if monthlySavings == 0:
        print("You should add more into your Savings account. ")
    if monthlyOverdraft == 0:
        print("Maintain not having an overdraft")
    if monthlySavings > monthlySpendings and overdraft > 0:
        print("Spend more money on essentials,instead of putting it into your savings. Ensure that you are not spending too much on essentials,as this can increase your overdraft")
    #if monthlySpending >==3 monthlySavings:
        #print("You are spending too much money in a month,add some money into savings. ")
    if monthlyOverdraft < 0:
        print("Add 15% of your monthly savings into paying off overdraft. ")
    if monthlyOverdraft > monthlySavings and monthlyOverdraft > monthlySpendings:
        print("Cut down on how much money goes into savings,and ensure that your overdraft is being paid off. ")
               

解决方法

def get_credit_score(self):
    Global monthlyWage
    monthlyWage = 2

def advice_to_be_given(self):
    print(monthlyWage)
,

您可以简单地在函数外定义它们,然后在要使用它们的函数内使用 global 关键字。

例如:

monthlyWage = 0
monthlySpendings = 0
monthlyOverdraft = 0
monthlySavings = 0 

def get_credit_score(self):
    global monthlyWage
    global monthlySpendings
    global monthlyOverdraft 
    global monthlySavings 
    monthlyWage = int(input("What is your monthly wage? "))
    monthlySpendings = int(input("What are your monthly spendings? ")) 
    monthlyOverdraft = int(input("What is your monthly overdraft? "))
    monthlySavings = int(input("How much do you add into your savings account per month? "))

他们变量出侧的功能可以由任何其他功能时,与全球关键字引用被使用

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。