在 python 中,函数创建一个新的作用域。如果在函数作用域内找不到变量,Python 会在外部(模块/文件)作用域中查找该变量。您可以通过赋值将变量添加到当前作用域中。这一切都意味着:
right = False
def func():
right = True
func()
print (right) #right is still False in the outer scope.
为了实际修改外部作用域中的变量,你需要告诉 python 你想要做类似的事情明确地:
right = False
def func():
global right
right = True
func()
print (right)
这可行,但不被认为是好的做法,因为您正在更改程序的状态。现在的价值right
取决于您是否调用了一个有点令人不安的函数。
在函数调用之间共享数据的更好方法是使用class。然后,方法(绑定到类实例的函数)可以更改该单个实例的状态,但程序的其余部分可以继续运行,就像什么都没发生一样。
class Foo(object):
def __init__(self):
self.right = False
def func(self):
self.right = True
a = Foo() #calls __init__ implicitly
print(a.right) #should be False -- We set this in __init__
a.func() #change state of `a`
print(a.right) #Now it's True!
这是代码的稍微“优雅”的版本:
import Tkinter as tk
class App(object):
def __init__(self):
self.right = False
self.left = False
self.up = False
def keyPressed(self,event):
print "HERE"
if event.keysym == 'Escape':
root.destroy()
elif event.keysym == 'Right':
self.right = True
elif event.keysym == 'Left':
self.left = True
elif event.keysym == 'Up':
self.up = True
def keyReleased(self,event):
if event.keysym == 'Right':
self.right = False
elif event.keysym == 'Left':
self.left = False
elif event.keysym == 'Up':
self.up = False
def task(self):
if self.right:
print 'Right'
elif self.left:
print 'Left'
elif self.up:
print 'Forward'
root.after(20,self.task)
application = App()
root = tk.Tk()
print( "Press arrow key (Escape key to exit):" )
root.bind_all('<Key>', application.keyPressed)
root.bind_all('<KeyRelease>', application.keyReleased)
root.after(20,application.task)
root.mainloop()