我试图写入一个.txt文件,但我得到了错误
File "C:\Python34\Timer.py", line 262, in Lap
outfile.write(timenow + str(tempo)+ "\n")
NameError: name 'outfile' is not defined
我已经在中定义了“outfile”:
class StopWatch(Frame):
""" Implements a stop watch frame widget. """
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw, bg="black")
self._start = 0.0
self._elapsedtime = 0.0
self._running = 0
self.timestr = StringVar()
self.lapstr = StringVar()
self.e = 0
self.m = 0
self.makeWidgets()
self.laps = []
self.lapmod2 = 0
self.today = time.strftime("%d %b %Y %H-%M-%S", time.localtime())
timenow = time.strftime("%d %b %Y %H:%M:%S", time.localtime())
outfile = open("lap_timings_and_time.txt","wt")
outfile.write(timenow+ "\n")
试图写入文件“lap\u timings\u And”_时间.txt'在以下代码中:
def Lap(self):
'''Makes a lap, only if started'''
tempo = self._elapsedtime - self.lapmod2
timenow = time.strftime("%d %b %Y %H:%M:%S", time.localtime())
if self._running:
self.laps.append(self._setLapTime(tempo))
self.m.insert(END, self.laps[-1])
self.m.yview_moveto(1)
self.lapmod2 = self._elapsedtime
outfile.write(timenow + str(tempo)+ "\n")
我是Python的初学者,不知道为什么会发生错误。非常感谢您的帮助!你知道吗
这应该是:
您还需要将构造函数(
__init__
)的最后两行更改为:更新:根据评论做一点解释。。。你知道吗
你所遇到的是“范围界定问题”。(见:Scoping and Namespaces)。你知道吗
通常,引用对象的属性需要“显式”引用。你知道吗
即:
不能通过表达式
return my_attr
引用my_attr
,因为my_attr
既不在Foo.foo()
范围内,也不在模块范围内,甚至不声明为全局。你知道吗相关问题 更多 >
编程相关推荐