【问题标题】:Return statement not working python 3返回语句不起作用python 3
【发布时间】:2015-05-09 17:15:30
【问题描述】:

这段代码的想法是,用户按下第一个按钮并输入他们想要的内容,然后按下第二个按钮并将其打印出来。有人可以告诉我为什么我的退货声明不起作用吗?它说没有定义“变量”。提前感谢您花时间阅读我的问题。

from tkinter import*

def fun():
    variable = input('Enter Here:')
    return variable


def fun_2():
    print(variable)


window = Tk()
button = Button(text = 'Button', command = fun )
button2 = Button(text = 'Button2', command = fun_2 )
button.pack()
button2.pack()


window.mainloop()

【问题讨论】:

    标签: python return


    【解决方案1】:

    在 python 中,当您在函数内创建变量时,它仅在该函数内定义。因此其他功能将无法看到它。

    在这种情况下,您可能需要对象内的某些共享状态。比如:

    class MyClass:
      def fun(self):
        self.variable = input('Enter Here:')
    
      def fun_2(self):
        print(self.variable)
    
    mc = MyClass()
    
    window = Tk()
    button = Button(text = 'Button', command = mc.fun )
    button2 = Button(text = 'Button2', command = mc.fun_2 )
    button.pack()
    button2.pack()
    

    【讨论】:

      【解决方案2】:

      fun() 可能会返回一个值,但 Tkinter 按钮不会执行任何具有该返回值的操作。

      请注意,我使用了短语返回一个值,而不是返回一个变量return 语句传回表达式的,而不是这里的variable 变量。因此,variable 变量不会变成其他函数可以访问的全局变量。

      在这里,您可以将variable 设为全局,并告诉fun 设置该全局:

      variable = 'No value set just yet'
      
      def fun():
          global variable
          variable = input('Enter Here:')
      

      由于您确实在 fun2variable 中使用了任何赋值,因此已经将其作为全局查找,现在它将成功打印 variable 的值,因为它现在可以找到该名称。

      【讨论】:

        【解决方案3】:

        问题出在fun2()。它没有将variable 作为输入参数。

        def fun_2(variable):
             print(variable)
        

        但请注意,您现在必须使用适当的参数调用 fun_2。此外,就目前的功能而言,如果您只是在其中进行打印,那么拥有该功能几乎没有意义。

        带走消息:变量在 Python 中不是全局变量,因此您必须将它传递给每个想要使用它的函数。

        【讨论】:

          猜你喜欢
          • 2017-11-04
          • 1970-01-01
          • 1970-01-01
          • 2020-04-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-23
          相关资源
          最近更新 更多