返回语句不起作用python 3 [英] Return statement not working python 3

查看:39
本文介绍了返回语句不起作用python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The idea of this code is, the user presses the first button and enters what they want, then they press the second button and it prints it out. Can someone please tell me why my return statement is not working? It says that 'variable' is not defined. Thanks in advance for taking the time to read my question.

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 中,当您在函数内部创建变量时,它仅在该函数中定义.因此其他功能将无法看到它.

In python when you create a variable inside of a function, it is only defined within that function. Therefore other functions will not be able to see it.

在这种情况下,您可能需要在对象中共享一些状态.类似的东西:

In this case, you will probably want some shared state within an object. Something like:

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()

这篇关于返回语句不起作用python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆