Python 修改函数中的变量没有结果

Python 修改函数中的变量没有结果,python,python-2.7,tkinter,return,global-variables,Python,Python 2.7,Tkinter,Return,Global Variables,我有一个Tkinter应用程序,所以我有典型的Tkinter的mainloop,还有各种处理鼠标点击和所有垃圾的功能 在其中一个函数中,我生成一个字符串,我想将该字符串存储在程序中的某个地方,以便以后调用其他函数时,或者如果我想从主循环打印它,我可以使用它 import this and that, from here and there etc etc #blah blah global declarations fruit = '' def somefunction(event):

我有一个Tkinter应用程序,所以我有典型的Tkinter的
mainloop
,还有各种处理鼠标点击和所有垃圾的功能

在其中一个函数中,我生成一个字符串,我想将该字符串存储在程序中的某个地方,以便以后调用其他函数时,或者如果我想从主循环打印它,我可以使用它

import this and that, from here and there etc etc
#blah blah global declarations


fruit = ''
def somefunction(event):
    blahblahblah; 

    fruit = 'apples'
    return fruit
mainwin = Tk()


#blah blah blah tkinter junk
#my code is here
#its super long so I don't want to upload it all
#all of this works, no errors or problems
#however
button = Button( blahblahblha)
button.bind("<button-1", somefunction)

print fruit

#yields nothing

mainwin.mainloop()
导入这个和那个,从这里和那里等等
#诸如此类的全球声明
水果=“”
定义函数(事件):
布拉布拉布拉赫;
水果=‘苹果’
还果
mainwin=Tk()
#废话废话
#我的密码在这里
#它太长了,所以我不想全部上传
#所有这些都有效,没有错误或问题
#然而
按钮=按钮(blahblahblha)

button.bind(“学习课程,你的问题就会消失。几乎所有这些封面课程都是一个Tkinter参考,你可以修改你的打字错误

导入系统 如果系统版本信息[0]<3: 将Tkinter作为tk##Python 2.x导入 其他: 将tkinter作为tk##Python 3.x导入 类StoreVariable(): 定义初始化(自,根): self.fruit='' 按钮=tk.按钮(根,bg=“lightblue”) button.grid() button.bind(“,self.somefunction) 按钮(root,text=“Exit”,bg=“orange”,command=root.quit).grid(row=1) def打印(自我): 打印自己的水果 定义函数(自身、事件): self.fruit=‘苹果’ 打印“换水果” mainwin=tk.tk() SV=存储变量(mainwin) mainwin.mainloop() ##假设一旦Tkinter退出,就会存储一些东西 ##请注意,您已退出Tkinter,但类实例仍然存在 水果 ##调用类的内置函数 SV.print_水果()
在函数中执行
fruit='anything'
时,它会将其指定为局部变量。当函数结束时,该局部变量将消失。如果要重新指定给全局变量,则需要使用
global
关键字来指示

def somefunction(event):
    global fruit # add this
    blahblahblah
    fruit = 'apples'
    return fruit
请注意,函数可以在不使用此行的情况下访问全局变量,但如果希望将相同名称的赋值应用于全局变量,则必须将其包括在内


另外,
“根据您的简化功能,以下是一些可能导致您出现问题的因素:

  • 您可能未将水果保存到主循环/程序内的变量。保存在函数内的值将在该函数完成后被擦除。除非您使用self.variable\u name将其保存在类变量内(如果您使用类,则适用)。如果不喜欢类,只需将其保存在主循环/函数内的变量中,如:

    fruit=somefunction()

    其他东西 打印水果#再次访问水果的时间

此语句位于主循环/程序中,您可以使用print再次访问它

  • 您可能正在使用其他语句/函数更改fruit的值。由于您尚未发布全部代码,因此不确定

这是一个相当长的问题。简洁会有更好的帮助。看看这个Q/a是否有助于TigerhawkT3谢谢你的精彩回答,它起作用了!谢谢你的回答和建议如果我们在酒吧,我会买啤酒、巧克力牛奶或其他东西,这实际上已经减少了近30行代码的开头和结尾les.谢谢!老实说,类一直是我的一个弱点。它不仅仅是python,我只是避免使用像瘟疫这样的类,因为我还没有真正了解它们的用途。每次我尝试使用它时,它都会使代码复杂化。(你能告诉我我不是一个狂热的程序员吗?括号中的笑声)
def somefunction(event):
    global fruit # add this
    blahblahblah
    fruit = 'apples'
    return fruit
button = Button(mainwin, text='blahblah', command=somefunction)