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

时间:2016-01-16 03:21:39

标签: python python-2.7 tkinter return global-variables

我有一个Tkinter应用程序,所以我有mainloop这是典型的Tkinter,以及处理鼠标点击和所有垃圾的各种函数。

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

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

这是一个简略的例子。程序中的其他所有工作都可以正常工作,我可以在整个程序中跟踪我的变量,但是当它被保存以供以后使用时,它会被删除。

例如,我可以打印变量,因为我将它从一个函数传递给另一个函数作为参数,它会没问题。它始终保存,并打印。我试图将它重新放回循环或存储以供以后使用,它会丢失或被覆盖(我不太确定是哪个)。

我真的不熟悉Python,所以我敢打赌,这是我错过的一些简单的事情。我假设这应该像所有其他语言一样工作,在那里你将一个字符串保存到一个全局变量,并且它将保留在那里直到你重置或重写它。

我目前的解决方法是创建一个文本文件并将字符串保存在其中,直到我需要它为止。

我在Windows 7上使用Python 2.7.11,但在Ubuntu上遇到了同样的问题。

3 个答案:

答案 0 :(得分:1)

在函数内部执行fruit = 'anything'时,它会将其指定为局部变量。当函数结束时,该局部变量消失。如果您想重新分配给全局变量,则需要使用global关键字表明您希望这样做。

def somefunction(event):
    global fruit # add this
    blahblahblah
    fruit = 'apples'
    return fruit

请注意,函数可以在没有此行的情况下访问全局变量,但是如果您希望将同名的赋值应用于全局变量,则必须包含它。

此外,"<button-1"应为"<button-1>"

此外,您应该只添加一个Button,而不是绑定到command

button = Button(mainwin, text='blahblah', command=somefunction)

单击Button窗口小部件时,不会将事件对象发送到他们绑定的函数,因此将somefunction定义为def somefunction():

此外,print fruit只执行一次。如果您想更改fruit然后查看新值,则必须在完成重新分配后将其打印为某个点。使用returnButton发送值不会执行任何操作,因为窗口小部件无法对其执行任何操作。这就是为什么Tkinter应用程序通常被创建为面向对象(OO)程序的原因,因此您可以轻松保存实例变量而无需使用global

答案 1 :(得分:0)

学习课程,你的问题就会消失。几乎所有这些涵盖类https://wiki.python.org/moin/BeginnersGuide/Programmers也是一个Tkinter参考,因此您可以修复拼写错误http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

import sys

if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x

class StoreVariable():
    def __init__(self, root):
        self.fruit = ''
        button = tk.Button(root, bg="lightblue")
        button.grid()
        button.bind("<Button-1>", self.somefunction)

        tk.Button(root, text="Exit", bg="orange", command=root.quit).grid(row=1)

    def print_fruit(self):
        print self.fruit

    def somefunction(self, event):
        self.fruit = 'apples'
        print "fruit changed"


mainwin = tk.Tk()
SV=StoreVariable(mainwin)
mainwin.mainloop()

## assume that once Tkinter exits there is something stored
## note that you have exited Tkinter but the class instance still exists
print SV.fruit
## call the class's built in function
SV.print_fruit()

答案 2 :(得分:0)

基于您的删节功能,以下是一些可能导致您出现问题的事情:

  • 您可能没有将水果保存到主循环/程序中的变量。一旦该功能完成,保存在函数内的值将被删除。除非您使用self.variable_name将其保存在类变量中(如果您使用的是类,则适用)。如果您不喜欢类,只需将其保存在主循环/函数内的变量中,如:

    fruit = somefunction()

    其他东西

    打印水果#再次访问水果的时间

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

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