【问题标题】:Cant access variables from a function无法从函数访问变量
【发布时间】:2022-01-10 15:11:54
【问题描述】:

这是我的代码中不起作用的部分:

current_month = datetime.now().month-1
current_year = datetime.now().year

def next_month():
    print("next month")
    if(current_month ==11):
        current_year = current_year + 1
        current_month = 0
    else:
        current_month = current_month + 1
        
    generate_calendar(current_year ,current_month)
    month_label.config(text=months[current_month])

def last_month():
    print("last month")
    if(current_month==0):
        current_year = current_year - 1
        current_month = 11
    else:
        current_month = current_month - 1 
    generate_calendar(current_year ,current_month)
    month_label.config(text=months[current_month])
    

问题是,该函数找不到任何东西(current_month 和 current_year)。我怎样才能让 python 知道这些变量不是局部变量? 我该如何解决?

附言 传递这些变量是行不通的,因为它们不会被改变。

【问题讨论】:

  • 您能否更新您的代码,使其成为minimal reproducible example?你提供的 sn-p 不会做任何事情,因为你没有调用你定义的任何一个方法。
  • 欢迎来到 Stack Overflow!请拨打tour。要获得调试帮助,您需要创建一个minimal reproducible example,包括完整但最少的代码、预期输出和实际输出——或者如果您遇到错误,则需要full error message with traceback。有关更多提示,请参阅How to Ask
  • 不要使用全局变量。要么将它们作为参数传递,要么检查创建类是否有意义。

标签: python function variables


【解决方案1】:

像这样尝试它会起作用。通常它可以使用 global 关键字声明变量也可以在方法中使用,但像我写的那样尝试。

from datetime import datetime
    

def next_month(current_month, current_year):
    print("next month")
    if(current_month ==11):
        current_year = current_year + 1
        current_month = 0
    else:
        current_month = current_month + 1
        
    generate_calendar(current_year ,current_month)
    month_label.config(text=months[current_month])

def last_month(current_month, current_year):
    print("last month")
    if(current_month==0):
        current_year = current_year - 1
        current_month = 11
    else:
        current_month = current_month - 1 
    generate_calendar(current_year ,current_month)
    month_label.config(text=months[current_month])


next_month(datetime.now().month-1, datetime.now().year)
last_month(datetime.now().month-1, datetime.now().year)

【讨论】:

  • 谢谢!工作。
  • 如果您满意,可以接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 2018-06-23
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多